首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将无限滚动添加到flutter FutureBuilder的GridView.builder

将无限滚动添加到flutter FutureBuilder的GridView.builder
EN

Stack Overflow用户
提问于 2021-07-31 15:35:59
回答 3查看 914关注 0票数 0

我很难把我的头围绕在颤动中无限滚动。我正在尝试先加载10个食谱,然后在ScrollController的帮助下显示新的食谱。当没有更多的食谱时,我想显示一条消息,表明没有更多的帖子。

这是我的项目代码。

代码语言:javascript
运行
复制
import 'package:flutter/material.dart';
import 'package:test/model/recipe.dart';
import 'package:test/pages/recipe_details.dart';
import 'package:test/widgets/recipe_card.dart';
import 'package:http/http.dart' as http;

class SingleCategory extends StatefulWidget {
  final Recipe recipe;
  final int recipeCourseid;
  final String recipeCourseName;

  SingleCategory({
    this.recipe,
    @required this.recipeCourseid,
    @required this.recipeCourseName,
  });

  @override
  _SingleCategoryState createState() => _SingleCategoryState();
}

class _SingleCategoryState extends State<SingleCategory> {
  ScrollController _scrollController = ScrollController();
  int pageNumber = 1;

  var myRecipe;

  Future<List<Recipe>> getRecipeList({int pageNumber}) async {
    // pageNum = 1;
    var response = await http.get(
        'https://test.com/wp-json/wp/v2/wprm_recipe?wprm_course=${widget.recipeCourseid}&per_page=10&$pageNumber');
    var body = response.body;
    final recipes = recipeFromJson(body)

    return recipes;
  }

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        pageNumber++;
        print(pageNumber);
        getRecipeList();
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.recipeCourseName),
          centerTitle: true,
          elevation: 5,
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 12.0),
          child: FutureBuilder(
            future: getRecipeList(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return GridView.builder(
                  controller: _scrollController,
                  itemCount: snapshot.data.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    crossAxisSpacing: 12.0,
                    mainAxisSpacing: 12.0,
                  ),
                  itemBuilder: (BuildContext context, int index) {
                    myRecipe = snapshot.data[index].recipe;
                    return InkWell(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => RecipeDetails(
                              recipe: snapshot.data[index],
                            ),
                          ),
                        );
                      },
                      child: RecipeCard(myRecipe: myRecipe),
                    );
                  },
                );
              } else if (snapshot.hasError) {
                return Center(
                  child: Text('There was an error, Please try again'),
                );
              } else {
                return Center(
                  child: CircularProgressIndicator(),
                );
              }
            },
          ),
        ),
      ),
    );
  }
}

如果你能给我指出正确的方向,我将不胜感激。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-07-31 16:09:12

一切看起来都很好,但你必须做一点小小的改变。

你的代码:

代码语言:javascript
运行
复制
_scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        pageNumber++;
        print(pageNumber);
        getRecipeList();
      }
    });

应该是:

代码语言:javascript
运行
复制
_scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        pageNumber++;
        setState(() {}); // if add this, Reload your futurebuilder and load more data
 //        getRecipeList(); // It's not necessary because, FutureBuilder call automatically getRecipeList when you call setState 
      }
    });
票数 0
EN

Stack Overflow用户

发布于 2021-07-31 16:07:37

尝试在你的GridView中添加

physics: const AlwaysScrollableScrollPhysics(),

票数 1
EN

Stack Overflow用户

发布于 2021-07-31 18:05:11

在类中声明一个新变量

代码语言:javascript
运行
复制
 List<Recipe> recipesList;

在getRecipeList()方法内部,如下所示

代码语言:javascript
运行
复制
Future<List<Recipe>> getRecipeList({int pageNumber}) async {
    // pageNum = 1;
If(page number ==1)
  recipesList.clear;

    var response = await http.get(
        'https://test.com/wp-json/wp/v2/wprm_recipe?wprm_course=${widget.recipeCourseid}&per_page=10&$pageNumber');
    var body = response.body;
    final recipes = recipeFromJson(body)
    recipesList.addAll(recipes);
    return recipesList;
  }

在scrollListener中,尝试传递pageNumber。因为您在getRecipesList方法内部和外部都为pageNumber声明了相同名称。

代码语言:javascript
运行
复制
_scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        pageNumber++;
        print(pageNumber);
        getRecipeList(pageNumber:pageNumber).then((){
            setState((){});
        });
      }
    });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68603523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档