如何将未来列表设置为列表并更新 ListView

Posted

技术标签:

【中文标题】如何将未来列表设置为列表并更新 ListView【英文标题】:How to set a future list to a list and update the ListView 【发布时间】:2020-02-12 06:21:26 【问题描述】:

每当我单击按钮时,我都需要更新列表视图, 我尝试了以下代码,但它不能完美运行, 当我单击第一个按钮时,它不会更新任何内容,当我单击第二个按钮时,它会使用第一个按钮列表更新列表,当我单击第三个按钮时,它会使用第二个按钮的列表更新列表。 这是我的代码

import 'package:flutter/material.dart';
import 'products_list.dart';


class HomeScreen extends StatefulWidget 
  @override
  _HomeScreenState createState() => _HomeScreenState();


class _HomeScreenState extends State<HomeScreen> 

  List<ProductsList> myinitlist = [];

  @override
  void initState() 
    super.initState();
myinitlist = List.from(productList);
  


  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Expanded(
                    child: Container(
                      child: SearchBar(),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(4.0, 4.0, 10.0, 4.0),
                    child: Hero(
                      tag: 'logo',
                      child: Image.asset(
                        'images/iglo_round.png',
                        height: 30.0,
                        width: 30.0,
                      ),
                    ),
                  ),
                ],
              ),
              Padding(
                padding: const EdgeInsets.all(5.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: FlatButton(
                        onPressed: () 
                          setState(() 

                          //i need to update this list with new items
                            myinitlist.removeRange(0, myinitlist.length);
                           getAllProductsInCategory(25504207);
                           myinitlist = List.from(productList);

                          );
                        ,
                        child: Container(
                          child: Column(
                            children: <Widget>[
                              Image.asset(
                                'images/bulb.png',
                                width: 100,
                                height: 100,
                              ),
                              Text('bulb')
                            ],
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: FlatButton(
                        onPressed: () 
                          setState(() 

              //i need to update this list with new items

                            myinitlist.removeRange(0, myinitlist.length);
                            getAllProductsInCategory(25504204);
                            myinitlist = List.from(productList);

                          );
                        ,
                        child: Container(
                          child: Column(
                            children: <Widget>[
                              Image.asset(
                                'images/bulb.png',
                                width: 100,
                                height: 100,
                              ),
                              Text('bulb')
                            ],
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: FlatButton(
                        onPressed: () 
                          setState(() 

                          //i need to update this list with new items

                            myinitlist.removeRange(0, myinitlist.length);
                            getAllProductsInCategory(25504208);
                            print(myinitlist.length);

                          );
                        ,
                        child: Container(
                          child: Column(
                            children: <Widget>[
                              Image.asset(
                                'images/bulb.png',
                                width: 100,
                                height: 100,
                              ),
                              Text('bulb')
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),


              Flexible(
                child: GridView.builder(itemCount: myinitlist.length,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount
                      (crossAxisCount: 2),
                    itemBuilder: (BuildContext context, int index)
                  return Card(
                    child: Stack(
                      children: <Widget>[
                        GestureDetector(
                          onTap:()
                          ,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[

                              Expanded(

                                child: Center(
                                  child: Image.network(myinitlist[index].proThummbnail,
                                    fit: BoxFit.contain,

                                  ),
                                ),
                                flex: 2,
                              ),
                              Expanded(
                                child: Center(child: Text(myinitlist[index].proName,
                                  style:
                                TextStyle(fontSize: 10.0),)),
                                flex: 1,
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                  );


                    ),

              ),


            ],
          ),
        ),
      ),
    );
  

products_list.dart 文件包含以下代码



List<ProductsList> productList = [];


class ProductsList

  int proId;
  String proName;
  String proThummbnail;

  ProductsList(@required this.proId,@required this.proName,@required this.proThummbnail);





Future<List<ProductsList>> getAllProductsInCategory(int catid) async

//  print(categoryList[0].catId);
  String prodInCategoryUrl = 'https://app.ecwid'
      '.com/api/v3/12424132/products?token'
      '=public_xxxxxxxxxxxx&enabled=true&category=$catid';


  Response allProductsInCategory = await get(prodInCategoryUrl);
  print(allProductsInCategory.statusCode);

  productList.removeRange(0, productList.length);

  if(allProductsInCategory.statusCode == 200)
  
    var allProductsInCategoryData = allProductsInCategory.body;

    int totalcount = jsonDecode(allProductsInCategoryData)['count'];

    for(int i=0;i<totalcount;i++)
    
//            print(jsonDecode(categoryData)['items'][i]['id']);
//            print(jsonDecode(categoryData)['items'][i]['name']);

      productList.add(
          ProductsList(proId: jsonDecode(allProductsInCategoryData)['items'][i]['id'],
              proName: jsonDecode(allProductsInCategoryData)
              ['items'][i]['name'], proThummbnail: jsonDecode
                (allProductsInCategoryData)
              ['items'][i]['thumbnailUrl']
          )
      );

    




    print('products list length $productList.length');

    return productList;

  

  return productList;;


谁能帮我解决这个问题。 提前谢谢你。

【问题讨论】:

【参考方案1】:

您的getAllProductsInCategory 是未来,因此您需要等待您的未来解决。尝试在它前面添加await。请注意,您可以在async 方法中使用await

【讨论】:

【参考方案2】:

更新此代码

setState(() 
   //i need to update this list with new items
   myinitlist.removeRange(0, myinitlist.length);
   getAllProductsInCategory(25504207);
   myinitlist = List.from(productList);
);

这样,(第一次更新onPressed: () async ...)//异步**

await getAllProductsInCategory(25504207);
setState(() 
   //i need to update this list with new items
   myinitlist.clear();
   myinitlist = List.from(productList);
);

【讨论】:

以上是关于如何将未来列表设置为列表并更新 ListView的主要内容,如果未能解决你的问题,请参考以下文章

如何自动选择列表中的项目?

单击列表视图时如何显示警报对话框

单击列表视图时如何显示警报对话框

如何使用 glide* 使用数组列表中的自定义适配器将图像设置为列表视图

如何动态更新用户列表[关闭]

如何将流生成器中的数据显示到文本字段中并更新来自列表视图?