Home > Back-end >  Flutter: How to update FloatingActionButton color on condition?
Flutter: How to update FloatingActionButton color on condition?

Time:04-12

I want to update the color of the FloatingActionButton on certain conditions(after the user update his values) I manage to set the color but only if the user click on the button where should I put the setstate or how can I achieve that?

FloatingActionButton.extended(
      onPressed: (){
        setState(() {
          if(departureCity!=null && arrivalCity!=null && bol){
            bol2=true;
            Navigator.push(
              context,
              //MaterialPageRoute(builder: (context) => const SeatScreen()),
              MaterialPageRoute(builder: (context) => BusSearchResults(departureCity,arrivalCity,_date)),
            );
          }
        });

      },
      label: const Text('Search'),
      backgroundColor: bol2? Color(0xff5348bf):Color(0xffd3d3d3) ,
    ),

CodePudding user response:

 bol2 = !bol2;

just write this instead of (bol2 = true ;) in your setState();

CodePudding user response:

Just change the value of bol2 to the opposite every time on click like given below. And try not to wrap everything in setState() since it's unnecessary.

FloatingActionButton.extended(
  onPressed: (){
    setState(() {
      if(bol2){
        bol2=false;
      }
      else{
        bol2=true;
      }
    });
    if(departureCity!=null && arrivalCity!=null){
      bol2=true;
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) =>BusSearchResults(departureCity,arrivalCity,_date)),
      );
    }
  },
  label: const Text('Search'),
  backgroundColor: bol2? Color(0xff5348bf):Color(0xffd3d3d3),
),
  • Related