如何从另一个小部件状态处理一个小部件状态?

问题描述 投票:0回答:3

我正在制作一个有购物车的轻量级应用程序。现在,当我们选择特定产品时,我只是在处理其单个功能,增加或减少其数量后,我们的购物车不会立即在购物车上显示该商品的数量。我们必须转到另一个小部件,然后它才能更新购物车中的数量。注意:HomeScreen包含两个有状态的小部件,一个是底部导航栏,其中具有购物车和其他图标以及其他图标以及它们各自的UI,另一个是Product屏幕,其中显示了我们所有的产品,在我的产品屏幕中,我使用了listview和在其UI中,我使用了-和+图标来增加或减少其数量。我正在共享小部件的代码-和+(产品屏幕的一小部分),我想在该代码上实现此功能。这是要显示的视频链接https://youtu.be/3qqVpmWguys

主屏幕:

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

class _HomeScreenState extends State<HomeScreen> {
  //static _HomeScreenState of(BuildContext context) => context.ancestorStateOfType(const TypeMatcher<_HomeScreenState>());
  int _currentindex = 0;
  var cart;

  final List<Widget> children = [
    ProductScreen(),
    OrderScreen(),
    CartScreen(),
    AccountScreen(),
  ];

  List<BottomNavigationBarItem> _buildNavigationItems() {
    var bloc = Provider.of<CartManager>(context);
    int totalCount = bloc.getCart().length;
    setState(() {
      totalCount;
    });

    return <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: Icon(
          Icons.reorder,
          size: 30,
          color: Colors.white,
        ),
        title: Text(
          'Product',
          style: TextStyle(fontSize: 15, color: Colors.white),
        ),
      ),
      BottomNavigationBarItem(
        icon: Icon(
          Icons.add_alert,
          size: 30,
          color: Colors.white,
        ),
        title: Text(
          'Order',
          style: TextStyle(fontSize: 15, color: Colors.white),
        ),
      ),
      BottomNavigationBarItem(
        icon: Stack(
          children: <Widget>[
            Icon(
              Icons.shopping_cart,
              size: 30,
              color: Colors.white,
            ),
            Positioned(
              bottom: 12.0,
              right: 0.0,

              child: Container(
                constraints: BoxConstraints(
                  minWidth: 20.0,
                  minHeight: 20.0,
                ),
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(10.0),
                ),
                child: Center(
                  child: Text(
                    '$totalCount',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
        title: Text(
          'Cart',
          style: TextStyle(fontSize: 15, color: Colors.white),
        ),
      ),
      BottomNavigationBarItem(
        icon: Icon(
          Icons.lock,
          size: 30,
          color: Colors.white,
        ),
        title: Text(
          'Account',
          style: TextStyle(fontSize: 15, color: Colors.white),
        ),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {

    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomPadding: true,
        body: children[_currentindex],
        bottomNavigationBar: BottomNavigationBar(
          fixedColor: Colors.transparent,
          backgroundColor: Colors.orange,
          onTap: onNavigationTapbar,
          currentIndex: _currentindex,
          items: _buildNavigationItems(),
          type: BottomNavigationBarType.fixed,
        ),
      ),
    );
  }

  void onNavigationTapbar(int index) {
    setState(() {
      _currentindex = index;
    });
  }
}

ProductScreen增量或减量:

class TEProductIncrementor extends StatefulWidget {
  var product;
  TEProductIncrementor({
    this.product,
  });

  @override
  _TEProductIncrementorState createState() => new _TEProductIncrementorState();
}

class _TEProductIncrementorState extends State<TEProductIncrementor> {
  int totalCount = 0;
  @override
  Widget build(BuildContext context) {
    var cartmanager = CartManager();
    void decrementsavecallback() {
 //     bloc.decreaseToCart(widget.ctlist);
//CartManager().updateToCart(totalCount.toString(), widget.ctlist);
      setState(() {
        if (totalCount > 0) {
          totalCount--;
          cartmanager.updateToCart(totalCount.toString(),widget.product);
        }
      });
    }

    void increasesavecallback() {
      setState(() {
          totalCount++;
          cartmanager.updateToCart(totalCount.toString(),widget.product);
      });
    }


      return Container(
          margin: EdgeInsets.only(top: 8),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10), color: Colors.orange),
          child: Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                IconButton(
                  iconSize: 30,
                  icon: new Icon(
                    Icons.remove,
                  ),
                  onPressed: () {
                  decrementsavecallback();
                  },
                ),
                Text(
                  totalCount.toString(),
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                IconButton(
                  iconSize: 30,
                  icon: new Icon(Icons.add),
                  onPressed: () {
                    increasesavecallback();
                  },
                )
              ],
            ),
          ),
        );
  }
}
flutter dart shopping-cart setstate
3个回答
0
投票

您可以为此使用BLoC模式,

Here是完整的答案和演示代码,您可以检查。


0
投票

您可以将整个功能传递到仅实现如下所示的小部件中

class Parent extends StatefulWidget {
  @override
  _ParentState createState() => _ParentState();
}

class _ParentState extends State<Parent> {
  @override
  Widget build(BuildContext context) {
    return Button(
        (){
          setState(() {
            ///define your logic here
          });
        }
    );
  }
}

class Button extends StatelessWidget {
  final Function onTap;
  Button(this.onTap);
  @override
  Widget build(BuildContext context) {
    return FlatButton(
      onPressed: onTap,
    );
  }
}

但是如果您的项目很大,那么我建议您使用任何状态管理库,例如redux或mobx。

https://pub.dev/packages/mobx


0
投票

为什么不使用钥匙?在两个小部件上分配一个GlobalKey,然后,当您需要更新该状态时,只需要调用

yourGlobalKeyName.currentState.setState((){
  //your code
});
© www.soinside.com 2019 - 2024. All rights reserved.