Home > OS >  Change text of a button when is pressed in flutter for a few seconds
Change text of a button when is pressed in flutter for a few seconds

Time:02-16

I'm trying to change the text of a button after is pressed for 2-3 seconds. So, if I press the button "SAVE GOALS", I want to change its text to "SAVED" for 2 seconds, and then back to "SAVE GOALS". I know how to change to "SAVED", but I dunno how to change back to SAVE GOALS. Delayed, sleep etc., nothing worked. I am in a stateful widget.

OutlinedButton(

                            onPressed: () {
                            setState(()  {
                              saveGoalsButtonText = "SAVED!";
                              Future.delayed(Duration(seconds: 3));
                              saveGoalsButtonText = "SAVE GOALS";
                            });
                            goals = _goalsController.text;
                            _saveGoals();
                            
                            //Navigator.pushReplacementNamed(context, '/masterclasses');
                          } ,
                          style: OutlinedButton.styleFrom(
                            primary: const Color(0xffE4BDB6),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(18.0),
                            ),
                            side: const BorderSide(width: 3, color: Color(0xffE4BDB6)),
                          ),

                          child:  Text(
                             saveGoalsButtonText,
                              style: const TextStyle(
                                color: Color(0xff221F1E),
                                fontSize: 14,
                                fontWeight: FontWeight.w700,
                              )
                          ),
                        ),

CodePudding user response:

you can do it like this:

onPressed: () {
              setState(()  {
                saveGoalsButtonText = "SAVED!";
              });
              Future.delayed(const Duration(seconds: 3), () {
                setState(() {
                  saveGoalsButtonText = "SAVE GOALS";
                });

              });

            } ,

the result:

enter image description here

  • Related