dart 我的Flutter列表显示相同的项目无限滚动

0lvr5msh  于 2023-07-31  发布在  Flutter
关注(0)|答案(1)|浏览(133)

我正在写我的第一个flutter项目,我有想法实现无限滚动。滚动单独工作,但它加载一遍又一遍的前10个项目,而不是下一个10。我已经检查了很多东西,但我有点用完的想法。
这是我的代码;

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:simple_news_app/Widgets/post.dart';
import 'package:simple_news_app/models/articles.dart';

class PostView extends StatefulWidget {
  final String query;
  const PostView({required this.query, super.key});

  @override
  State<PostView> createState() => _PostViewState();
}

class _PostViewState extends State<PostView> {
  late Future<List<Article>> news;
  bool isLoading = true;
  int page = 1;
  ScrollController scrollController = ScrollController();
  String publicKey = "febf23615942406cb62faff8a0f8767d";
  Future<List<Article>> initialFetch() async {
    final res = await http.get(Uri.parse(
        "https://newsapi.org/v2/everything?q=${widget.query}&apiKey=$publicKey&pageSize=10&page=1"));

    if (res.statusCode == 200) {
      Map<String, dynamic> json = jsonDecode(res.body);
      isLoading = false;

      List<dynamic> body = json['articles'];

      List<Article> articles =
          body.map((dynamic item) => Article.fromJson(item)).toList();

      return articles;
    } else {
      throw ("Can't get the Articles");
    }
  }

  void fetchMore() async {
    final res = await http.get(Uri.parse(
        "https://newsapi.org/v2/everything?q=${widget.query}&apiKey=$publicKey&pageSize=10&page=1"));

    if (res.statusCode == 200) {
      Map<String, dynamic> json = jsonDecode(res.body);
      isLoading = false;
      List<dynamic> body = json['articles'];
      List<Article> articles =
          body.map((dynamic item) => Article.fromJson(item)).toList();

      setState(() {
        news.then((value) => value.addAll(articles));
      });
    } else {
      throw ("Can't get the Articles");
    }
  }

  @override
  void initState() {
    super.initState();
    news = initialFetch();
    scrollController.addListener(scrollListener);
  }

  void scrollListener() {
    if (scrollController.position.pixels ==
        scrollController.position.maxScrollExtent) {
      page = page + 1;
      fetchMore();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Results for searching: ${widget.query}"),
        ),
        body: Container(
          decoration:
              BoxDecoration(color: Theme.of(context).colorScheme.secondary),
          child: FutureBuilder<List<Article>>(
            future: news,
            builder: (context, snapshot) {
              if (snapshot.hasData && !isLoading) {
                return ListView.builder(
                  controller: scrollController,
                  itemCount: snapshot.data!.length + 1,
                  itemBuilder: (context, index) {
                    if (index < snapshot.data!.length) {
                      final article = snapshot.data![index];
                      return Column(
                        children: [
                          Text(snapshot.data!.length.toString()),
                          Post(
                            article: article,
                          )
                        ],
                      );
                      // return Post(
                      //   article: article,
                      // );
                    } else {
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }
                  },
                );
              }
              if (snapshot.hasError) {
                return Text(snapshot.toString());
              }
              return const Center(
                child: CircularProgressIndicator(),
              );
            },
          ),
        ));
  }
}

字符串
我真的很感激你们的帮助!
我的期望是加载越来越多的职位,当我达到一个屏幕的结束一遍又一遍

dgiusagp

dgiusagp1#

我希望这可以帮助,我改变了一些代码,因为我需要自己尝试。

import 'dart:convert';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

@RoutePage()
class PostView extends StatefulWidget {
  const PostView({super.key});

  @override
  State<PostView> createState() => _PostViewState();
}

class _PostViewState extends State<PostView> {
  bool isLoading = true;
  int page = 1;
  ScrollController scrollController = ScrollController();
  String publicKey = "febf23615942406cb62faff8a0f8767d";
  Future<List<dynamic>> fetchData(int page) async {
    final res = await http.get(Uri.parse(
        "https://newsapi.org/v2/everything?q=baby&apiKey=$publicKey&pageSize=10&page=$page"));

    if (res.statusCode == 200) {
      Map<String, dynamic> json = jsonDecode(res.body);
      isLoading = false;

      List<dynamic> body = json['articles'];
      return body;
    } else {
      throw ("Can't get the Articles");
    }
  }

  late Future<List<dynamic>> news;
  @override
  void initState() {
    super.initState();
    scrollController.addListener(scrollListener);
    news = fetchData(page);
  }

  void scrollListener() {
    if (scrollController.position.pixels ==
        scrollController.position.maxScrollExtent) {
      page = page + 1;
      news = fetchData(page);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Results for searching: user"),
        ),
        body: Container(
          decoration:
              BoxDecoration(color: Theme.of(context).colorScheme.secondary),
          child: FutureBuilder<List<dynamic>>(
            future: news,
            builder: (context, snapshot) {
              print(snapshot);
              if (snapshot.hasData && !isLoading) {
                return ListView.builder(
                  controller: scrollController,
                  itemCount: snapshot.data!.length + 1,
                  itemBuilder: (context, index) {
                    if (index < snapshot.data!.length) {
                      final article = snapshot.data![index];
                      return Column(
                        children: [
                          Text(snapshot.data!.length.toString()),
                          Text(article.toString()),
                        ],
                      );
                      // return Post(
                      //   article: article,
                      // );
                    } else {
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }
                  },
                );
              }
              if (snapshot.hasError) {
                return Text(snapshot.toString());
              }
              return const Center(
                child: CircularProgressIndicator(),
              );
            },
          ),
        ));
  }
}

字符串

相关问题