Stateful Widget updation on calling it with different parameters, not updating?

1,047

Solution 1

Try the code below:

void main() {
  runApp(App());
}

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  @override
  String homeText = "default";
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
        home: new Scaffold(backgroundColor: Colors.blueGrey.shade100,
      body: Home.Homescreen(HomeText: homeText,), //initially setting text to default
      appBar: new AppBar(
        centerTitle: true,
        title: new Text("newApp",
            textDirection: TextDirection.ltr,
            style: TextStyle(fontSize:20 ,color: Colors.white)),
      ),
      bottomNavigationBar: new BottomNavigationBar(items: [
        new BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: new Text(
              "Home",
              textDirection: TextDirection.ltr,
            )),
        new BottomNavigationBarItem(
            icon: Icon(Icons.face),
            title: new Text(
              "Profile",
              textDirection: TextDirection.ltr,
            )),
        new BottomNavigationBarItem(
            icon: Icon(Icons.exit_to_app),
            title: new Text(
              "Exit",
              textDirection: TextDirection.ltr,
            )),
      ],onTap: (int item){
        if(item == 0){
          setState(() {
            homeText = "this is home"; 
          });
        }
        else if(item == 1){
          setState(() {
            homeText = "this is profile";
          });

        }
        else if(item == 2){
          setState(() {
            homeText = "this is exit";
          });
        }
      },),
    ));
  }
}

The problem you have is you're not changing your body when you call setState. When build method runs, It always has the same body. With the code above, You update the homeText value and when the build method runs, the homeText has a new value and your text is updated.

Solution 2

Try passing a key, it should help you I believe:

Home.Homescreen(HomeText:'this is proile', key: key: ValueKey('this is proile') );

Add key and pass it to super in Homescreen:

class Homescreen extends StatefulWidget{
  Homescreen({Key key, this.HomeText}) : super(key: key); // init hometext
  String HomeText;

  @override
  _Homescreen createState() => _Homescreen();

}

key should be something unique to let it know that it should update. Here are a couple links about statefull widgets and keys:

https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html

https://www.youtube.com/watch?v=kn0EOS-ZiIc&app=desktop

https://medium.com/@ayushpguptaapg/using-keys-in-flutter-1c5fb586b2a5

Share:
1,047
ArcaneAce
Author by

ArcaneAce

Updated on December 12, 2022

Comments

  • ArcaneAce
    ArcaneAce over 1 year

    i just started learning flutter, im using Stateful widget the following code below is the main.dart file

    void main() {
      runApp(App());
    }
    
    class App extends StatefulWidget {
      @override
      _AppState createState() => _AppState();
    }
    
    class _AppState extends State<App> {
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return MaterialApp(
            home: new Scaffold(backgroundColor: Colors.blueGrey.shade100,
          body: Home.Homescreen(HomeText: "default",), //initially setting text to default
          appBar: new AppBar(
            centerTitle: true,
            title: new Text("newApp",
                textDirection: TextDirection.ltr,
                style: TextStyle(fontSize:20 ,color: Colors.white)),
          ),
          bottomNavigationBar: new BottomNavigationBar(items: [
            new BottomNavigationBarItem(
                icon: Icon(Icons.home),
                title: new Text(
                  "Home",
                  textDirection: TextDirection.ltr,
                )),
            new BottomNavigationBarItem(
                icon: Icon(Icons.face),
                title: new Text(
                  "Profile",
                  textDirection: TextDirection.ltr,
                )),
            new BottomNavigationBarItem(
                icon: Icon(Icons.exit_to_app),
                title: new Text(
                  "Exit",
                  textDirection: TextDirection.ltr,
                )),
          ],onTap: (int item){
            if(item == 0){
              setState(() {
                Home.Homescreen(HomeText:'this is home'); /* this should change homescreen text but it still says default same for all the below as well*/
              });
            }
            else if(item == 1){
              setState(() {
                Home.Homescreen(HomeText:'this is proile');
              });
    
            }
            else if(item == 2){
              setState(() {
                Home.Homescreen(HomeText:'this is exit');
              });
            }
          },),
        ));
      }
    }
    

    in this a Stateless widget 'App' is called and in _AppState in the Scaffold the body is assigned to a Stateless Widget 'HomeScreen' exported as Home in main under BottomNavigationBar the the items are assigned an int to them which on tapping should change the HomeText accordingly but it does not update , it remains the same on homescreen just saying "default" which is what it was initially called with, the following code is of the home_screen.dart which is called

    class Homescreen extends StatefulWidget{
      Homescreen({this.HomeText}); // init hometext
      String HomeText;
      @override
      _Homescreen createState() => _Homescreen();
    
    }
    
    class _Homescreen extends State<Homescreen>{
    
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return new Center(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              new Text(
                widget.HomeText, // this is what should be updated when called
                textDirection: TextDirection.ltr,
                style: new TextStyle(fontSize: 30,color: Colors.black),
              )
            ],
          ),
        );
      }
    }
    

    i dont understand why is the hometext not updating when the icons(bottomnavigationbaritems) are tapped , i've tested the values using debugprint they return 0,1,2 .So,Thats atleast correct.

  • ArcaneAce
    ArcaneAce about 4 years
    Thank you! now i understand that by changing the value of homeText the whole widget "App" get rebuild with the updated homeText value.
  • Morez
    Morez about 4 years
    The rebuilding happens because of the setState. Whenever setState is called in a StatefulWidget, The build method runs again. Have a look at api.flutter.dev/flutter/widgets/State/setState.html for more details about setState.