在 Flutter 中如何通过页面 id 创建自动无限滚动分页?

Posted

技术标签:

【中文标题】在 Flutter 中如何通过页面 id 创建自动无限滚动分页?【英文标题】:In Flutter how to create auto infinite scroll pagination by page id? 【发布时间】:2021-12-05 18:41:48 【问题描述】:

我正在尝试使用自动滚动创建分页,但是使用此模型(在底部),我无法做到吗?我是这里的初学者,我从头到尾都在努力尝试,但不幸的是无法找到。那么有人可以帮我在这个颤动的屏幕上创建无限的自动滚动分页吗? 这是我的测试屏幕代码:

class Test extends StatefulWidget 

  Test(Key key) : super(key: key);

  @override
  createState() => _Test();


class _Test extends State<Test3> 
  Future<getTotalLeadsListss> getLeads;
  String _value='total';
  @override
  void initState() 
    super.initState();
    loading=false;
    getLeads=_getDatacall();
  
  int page =1;
  ScrollController _scrollController = new ScrollController();

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      body: Center(
        child: FutureBuilder<getTotalLeadsListss>(
          future: _getDatacall(),
          builder: (context, snapshot) 
            if (snapshot.hasData) 
              var dataB =snapshot.data;
              return dataB.leadFollowupss.length<=0?
              Center(child: Column(
                children: [
                  Image(image:AssetImage(Assets.noDataImg),)
                ],
              )):
              ListView.builder(
                  controller: _scrollController,
                  itemCount:dataB.leadFollowupss.length,
                  itemBuilder: (BuildContext context, int index)
                    return Container(
                        margin: EdgeInsets.only(left: 8.0,right: 8.0,top: 3.0,bottom: 3.0),
                        child: GestureDetector(
                            onTap:(),
                            child: Card(
                                color: Colors.grey,
                                elevation: 2.0,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(5.0),
                                ),
                                child: ListTile(
                                  contentPadding: EdgeInsets.only(left:8.0,right:8.0),
                                  title: new Text(dataB.leadFollowupss[index].name,maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    softWrap: false,
                                    style: TextStyle(
                                        fontSize: 18.0,fontWeight: FontWeight.w600),
                                  ),
                                  subtitle: Text(
                                    dataB.leadFollowupss[index].nextMeeting.toString(),
                                    style: TextStyle(),
                                  ),
                                )
                            )
                        )
                    );
                  
              );
            
            else if (snapshot.hasError) 
              return Text("$snapshot.error");
             else if (snapshot.connectionState==ConnectionState.waiting)
              return Container(child: Center(child: Image(image:AssetImage(Assets.loaderImg),)));
            
            return Container(child: Center(child: Image(image:AssetImage(Assets.loaderImg),)));
          ,
        )
      ),

    );
  
  Future<getTotalLeadsListss> _getDatacall()async
    TotalLeadsListss wrapper = new TotalLeadsListss();
    return wrapper.getAllLeadsListss(_value,page);
  


/// get all leads list
class TotalLeadsListss 
  String _value;
  Future<getTotalLeadsListss> getAllLeadsListss(_value,page) async 
    final response  = await http.post(Uri.parse('$mainUrllead-list'),
        headers:
          'Accept': 'application/json',
          HttpHeaders.authorizationHeader: 'Bearer $accessToken',
        ,
        body: 
          'type':'$_value',
          'page':'$page',
        
    );
    if (response.statusCode == 200) 
      String  data = response.body;
      return getTotalLeadsListss.fromJson( json.decode(response.body) );
     else 
      print('failed to get data');
      throw Exception('No records found');
    
  


class getTotalLeadsListss 
  bool status;
  String msg;
  List<LeadFollowupss> leadFollowupss;

  getTotalLeadsListss(this.status, this.msg, this.leadFollowupss);

  getTotalLeadsListss.fromJson(Map<String, dynamic> json) 
    status = json['status'];
    msg = json['message'];
    if (json['data'] != null) 
      leadFollowupss = new List<LeadFollowupss>();
      json['data'].forEach((v) 
        leadFollowupss.add(new LeadFollowupss.fromJson(v));
      );
    
  

  Map<String, dynamic> toJson() 
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    data['message'] = this.msg;
    if (this.leadFollowupss != null) 
      data['data'] = this.leadFollowupss.map((v) => v.toJson()).toList();
    
    return data;
  

class LeadFollowupss 

  String id,name,nextMeeting;

  LeadFollowupss(
      this.id,this.name,this.nextMeeting);

  LeadFollowupss.fromJson(Map<String, dynamic> json) 
    id = json['id'];
    name = json['business_name'];
    nextMeeting=json['next_meeting'];
  

  Map<String, dynamic> toJson() 
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['business_name'] = this.name;
    data['next_meeting'] = this.nextMeeting;
    return data;
  

【问题讨论】:

【参考方案1】:

你需要听ScrollController

class MyHome extends StatefulWidget 
  @override
  _MyHomeState createState() => _MyHomeState();


class _MyHomeState extends State<MyHome> 
  late ScrollController controller;
  List<String> items = List.generate(20, (index) => 'item $index');

  @override
  void initState() 
    super.initState();
    controller = ScrollController()..addListener(_scrollListener);
  

  @override
  void dispose() 
    controller.removeListener(_scrollListener);
    super.dispose();
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        child: ListView.builder(
          controller: controller,
          itemBuilder: (context, index) 
            return Text(items[index]);
          ,
          itemCount: items.length,
        ),
    );
  

  void _scrollListener() 
    print(controller.position.extentAfter);
    if (controller.position.extentAfter < 500) 
      setState(() 
        items.addAll(List.generate(20, (index) => 'item $index'));
      );
    
  

如果您从setState 中的服务器请求数据中获取数据,并且在用户向下滚动时需要每个范围

【讨论】:

感谢您的快速回复,但这还不足以让我理解嵌套对象 API。如果可能,请以其他方式解释。

以上是关于在 Flutter 中如何通过页面 id 创建自动无限滚动分页?的主要内容,如果未能解决你的问题,请参考以下文章

在 Firestore 查询中 Flutter 传递文档 ID

如何自动化 Flutter 应用程序

如何通过 Facebook 移动应用程序在 Flutter 应用程序中将链接(或图像)与用户管理的 Facebook 页面共享

flutter 自动刷新token

在flutter中使用getX打开页面时自动调整页面语言

Flutter/IOS混和开发情况下,项目内首个Flutter页面导航无返回问题