Search code examples
dartstateflutterternary

Dart / Flutter Page Not Reloading After SetState?


I have a follow / unfollow button that changes the UI depending on the value of a public string. The problem is after the value of the String has changed and setState is called the UI remains the same. If I reload the page then it may change. Here is my code...

var friends;

Future<Null> follow() async{
friends = "Friends"
setState((){});
}

Future<Null> unfollow() async{
friends = "Not Friends"
setState((){});
}

@override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          backgroundColor: Colors.amber,
          title: new Text(
            'Friends',
            ),
          ),
        ),
        body: new Container(


         // Unfollow and Message

                friends == "Friends" ? new RaisedButton(
                      onPressed: unfollow,
                      child: new Row(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          new Icon(
                            Icons.not_interested,
                          ),
                          new Text(
                            "UNFOLLOW",
                          )
                        ],
                      ),
                    ) :

                  new RaisedButton(
                  onPressed: follow,
                  child: new Row(
                    children: <Widget>[
                      new Icon(
                        Icons.thumb_up,
                      ),
                      new Text(
                        "FOLLOW",
                      )
                    ],
                  ),
                ),

I'm trying to show either a follow or unfollow RaisedButton depending on the value of "friends" and its not working. I'm not sure if it's the way I'm setting my State or if my Ternary operator is written incorrectly. Please help!


Solution

  • To set the state, add your logic inside setState() method. Anyway, when I'm looking at your code, I don't think you need to use async, but you can change it back.

    void unfollow(){
      setState(() =>friends = "Not Friends");
    }