【问题标题】:Flutter: List<Map<String, dynamic>> doesn't update ui颤振: List<Map<String, dynamic>> 不更新 ui
【发布时间】:2021-12-25 07:25:14
【问题描述】:

我的职能是增加产品数量。首先,我使用包含 nameamountList&lt;Map&lt;String, dynamic&gt;&gt; 将每个产品及其类别分开。当我点击 + 按钮时,它可以在控制台中正确打印增加的数字。但是在 ui 中,产品的数量不会立即改变。需要点击ExpansionTile折叠,再次点击展开,数量会增加。

这是我创建ExpansionTile的代码。

ListView.builder(
   shrinkWrap: true,
   physics: NeverScrollableScrollPhysics(),
   itemCount: categories.length,
   itemBuilder: (context, index) {
   return Container(
      margin: EdgeInsets.only(bottom: 10),
      decoration: BoxDecoration(
         borderRadius: BorderRadius.circular(10),
         color: CollectionsColors.purple,
      ),
      child: ExpansionTile(
         title: Text(
            categories[index],
            style: FontCollection.bodyBoldTextStyle,
         ),
         children: [
            Container(
               color: CollectionsColors.white,
               child: listData(categories[index]),
            ),
         ],
       ),
    );
  },
)

这是在 ExpansionTile 中创建产品列表的代码。

Widget listData(String category) {
    ProductNotifier productNotifier = Provider.of<ProductNotifier>(context);
    List<Map<String, dynamic>> products = [];

    productNotifier.productList.forEach((product) {
      if (product.category == category) {
        products.add({'name': product.name, 'amount': 0});
      }
    });
    print(products);

    return ListView.separated(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: products.length,
      itemBuilder: (context, index) {
        return Container(
          margin: EdgeInsets.only(bottom: 5),
          padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                child: Text(
                  products[index]['name'],
                  style: FontCollection.bodyBlackTextStyle,
                ),
              ),
              Container(
                  key: UniqueKey(),
                  child: CustomStepper(
                      value: products[index]['amount'],
                      iconSize: 25,
                      increaseAmount: () {
                        products[index].update('amount', (value) => ++value);
                        print(products);
                      }
                  )),
            ],
          ),
        );
      },
    );
  }

当我在牵牛花中单击+ 按钮时,它会在控制台中正确打印。

[{name: Morning Glory, amount: 1}, {name: Collard greens, amount: 0}, {name:  Cucumber, amount: 0}, {name: Carrot, amount: 0}]

但在ui中并没有将值改为1。我需要点击ExpansionTile折叠并再次点击展开,然后数字会改变。

【问题讨论】:

    标签: list flutter dart


    【解决方案1】:

    试试这样:

    import 'package:flutter/material.dart';
    
    class ClassName extends StatefulWidget {
      static const String routeName = "/s-test";
    
      const ClassName({Key? key}) : super(key: key);
    
      @override
      _ClassNameState createState() => _ClassNameState();
    }
    
    class _ClassNameState extends State<ClassName> {
      List<Map<String, dynamic>> products = [];
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
          setState(() {
            ProductNotifier productNotifier = Provider.of<ProductNotifier>(context, listen:false);
            productNotifier.productList.forEach((product) {
              if (product.category == category) {
                products.add({'name': product.name, 'amount': 0});
              }
            });
          });
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: categories.length,
            itemBuilder: (context, index) {
              return Container(
                margin: EdgeInsets.only(bottom: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  color: CollectionsColors.purple,
                ),
                child: ExpansionTile(
                  title: Text(
                    categories[index],
                    style: FontCollection.bodyBoldTextStyle,
                  ),
                  children: [
                    Container(
                      color: CollectionsColors.white,
                      child: listData(categories[index]),
                    ),
                  ],
                ),
              );
            },
          ),
        );
      }
    
      Widget listData(String category) {
        return ListView.separated(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemCount: products.length,
          itemBuilder: (context, index) {
            return Container(
              margin: EdgeInsets.only(bottom: 5),
              padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    child: Text(
                      products[index]['name'],
                      style: FontCollection.bodyBlackTextStyle,
                    ),
                  ),
                  Container(
                      key: UniqueKey(),
                      child: CustomStepper(
                          value: products[index]['amount'],
                          iconSize: 25,
                          increaseAmount: () {
                            setState(() {
                              products[index].update('amount', (value) => ++value);
                              print(products);
                            });
                          })),
                ],
              ),
            );
          },
        );
      }
    }
    

    【讨论】:

    • 我尝试使用setState(),但是当我点击每个产品上的增加按钮时,它只打印了1,但没有像amount += 1那样增加。
    • 这是我点击牵牛花[{name: Morning Glory, amount: 1}, {name: Collard greens, amount: 0}, {name: Cucumber, amount: 0}, {name: Carrot, amount: 0}]时控制台中的打印结果@
    • 当我点击下一个产品时[{name: Morning Glory, amount: 0}, {name: Collard greens, amount: 1}, {name: Cucumber, amount: 0}, {name: Carrot, amount: 0}]
    • 以上示例答案适合您吗?
    • 不,它不起作用
    猜你喜欢
    • 2021-11-20
    • 2021-04-13
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    相关资源
    最近更新 更多