Moulik Gupta 50
Moulik Gupta 50

Reputation: 186

StatefulBuilder's setState function not changing the color of IconButton

I'm making an Instagram clone app and I'm trying to use StatefulBuilder but the setState function of the builder does not change the color of the Container wrapped in GestureDetector ( onTap function ).

StatefulBuilder(
                        builder: (context, setState) {
                          var color = Color.fromRGBO(38, 38, 38, 1);
                          return Flexible(
                            flex: 1,
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  color = Color.fromRGBO(0, 149, 246, 1);
                                });
                              },
                              child: Container(
                                alignment: Alignment.center,
                                height: 30,
                                // width: double.infinity,
                                decoration: BoxDecoration(
                                    borderRadius: const BorderRadius.all(
                                      Radius.circular(10),
                                    ),
                                    color: color),
                                child: const Text('Follow'),
                              ),
                            ),
                          );
                        },
                      )

I want the Follow button to change it's color but I don't want to use the setState of the Stateful Widget as I don't want to rebuild the whole screen. Am I using StatefulBuilder incorrectly or is there any other solution to my problem?

Upvotes: 0

Views: 79

Answers (2)

eamirho3ein
eamirho3ein

Reputation: 17880

You define your color variable inside your StatefulBuilder, and every time you call setState it resets this value and set the default value to it, you need to define it out of StatefulBuilder, like this:

var color = Color.fromRGBO(38, 38, 38, 1);

StatefulBuilder(
   builder: (context, setState) {
       return Flexible(
    ...
)

Upvotes: 1

Balaji
Balaji

Reputation: 2077

 var color = Color.fromRGBO(38, 38, 38, 1);

above line should be outside of StatefulBuilder

Upvotes: 1

Related Questions