How to handle a one widget state from another widget state?

1,027

You can pass the entire function into a widget just implemented like below

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,
    );
  }
}

But if your project is pretty big then I will recommend you to use any state management libraries just like redux or mobx.

https://pub.dev/packages/mobx

Share:
1,027
Umair
Author by

Umair

Updated on November 30, 2022

Comments

  • Umair
    Umair over 1 year

    I am making a flutter application that have shopping cart. Right now, i am just working on a single functionality of it when we select a particular product, after increase or decrease its quantity then our cart doesnot show the quantity of that item on the cart immediately. we have to go to another widget then it update the count on cart. Note: HomeScreen comprise of two stateful widget, one is bottom navigation bar which have cart and other icons along with other icons and their respective UI's and other one is Product screen which is showing all our products, and in my product screen i used listview and in its UI i used - and + icons to increase or decrease its quantity. I am sharing the code of the widget - and +(a small portion of product screen) on which i want to implement this functionality. This is the video link to show https://youtu.be/3qqVpmWguys

    HomeScreen:

    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 incrementor or decrementor:

    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();
                      },
                    )
                  ],
                ),
              ),
            );
      }
    }
    
    • Salma
      Salma over 4 years
      why not use a cart stream in the bloc and streambuilder for the cart widget? you can pass the bloc object in the bigger widget to the smaller one and update it there as well
    • Umair
      Umair over 4 years
      Yes, for me that worked. Thankyou for the help
  • Umair
    Umair over 4 years
    In bloc pattern, can we handle states of more than two widgets simaltaneously?. Because i am using two different stateful widget one have bottom navigation bar and other have product screen.
  • Devarsh Ranpara
    Devarsh Ranpara over 4 years
    Yes you can manage more then one state with bloc pattern, You need to create multiple streams and multiple stream builders, If you don't want to use BloC pattern you can use Inherited Widget and use state of another class from almost anywhere. You can reference above link for inherited widget github.com/devarshranpara/flutter_showcaseview/blob/master/l‌​ib/…