简体   繁体   English

数据未更新到另一个小部件颤动

[英]Data not updating to another widget flutter

I am trying to show the price of items in the cart but the total value should be shown in TextField.我试图显示购物车中商品的价格,但总价值应显示在 TextField 中。 I am saving data to SQLite and retrieving then show to a widget, but when I try to access total_price to another widget it's not updating, but When I press hot reload again the data shows but not first time when I am opening the page我正在将数据保存到 SQLite 并检索然后显示到小部件,但是当我尝试将total_price访问到另一个小部件时它没有更新,但是当我再次按下热重载时,数据显示但不是第一次打开页面时

  return FutureBuilder<List<CartModel>>(
      future: fetchCartFromDatabase(),
      builder: (context, snapshot) {

        if (snapshot.hasData && snapshot.data.length > 0) {
           cartCount = snapshot.data.length;
           for(int i = 0;i<snapshot.data.length;i++){
            var price = snapshot.data[i].product_price.split("₹");
            total_price+=double.parse(price[1]);
          }
  } else if (snapshot.hasData && snapshot.data.length == 0) {
          return new Text("No Data found");
        }
        else
          {
            return new Container(
              alignment: AlignmentDirectional.center,
              child: new CircularProgressIndicator(),
            );
          }
);

value initialized值已初始化

  int cartCount = 0;
  double total_price=0.0;

The FutureBuilder updates only its children. FutureBuilder只更新它的孩子。 To update the value of another widget you must use setState.要更新另一个小部件的值,您必须使用 setState。

The best way would be putting FutureBuilder in an upper level or using some sort of state manager, like provider.最好的方法是将 FutureBuilder 放在上层或使用某种状态管理器,如提供者。

To use setState you need to initialize you fetch from an initState of a stetefullWidget (or to call it from a function).要使用 setState,您需要初始化您从 stetefullWidget 的 initState 获取(或从函数调用它)。 This way you will not need a FutureBuilder and must refactor your code:这样你就不需要 FutureBuilder 并且必须重构你的代码:

class YourWidget extends StatefulWidget {
  @override
  _YourWidgetState createState() => _YourWidgetState();
}

class _YourWidgetState extends State<YourWidget> {
  double total_price = 0;

  @override
  void initState() {
    super.initState();
    fetchCartFromDatabase().then((value){
      setState((){
        for(int i = 0;i<value.length;i++){
          var price = value[i].product_price.split("₹");
          total_price+=double.parse(price[1]);
        } 
      });
    });
  }
}

The addPostFrameCallback is not a good solution, since it updates the value only in the next frame. addPostFrameCallback 不是一个好的解决方案,因为它只在下一帧更新值。 When the app grows it leads to lags.当应用程序增长时,它会导致滞后。

To continue using the FutureBuilder, move your widget tree that needs to be updated to be inside of the FutureBuilder.要继续使用 FutureBuilder,请将需要更新的小部件树移动到 FutureBuilder 内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM