Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can view FloatingActionButton on condition

Tags:

flutter

I have list of orders orderList. If that isEmpty, FloatingActionButton is hide. In case orderList have products - FAB will be shown. My code:

bool statusFAB = false;   

_getFABState(){
        setState(() {
          if(!orderList.isEmpty){
            statusFAB = true;
          }
        });
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          floatingActionButton: _getFAB(),
          backgroundColor: _kAppBackgroundColor,
          body: Builder(
            builder: _buildBody,
          ),
        );

      Widget _getFAB() {
        if(statusFAB){
          return FloatingActionButton(
              backgroundColor: Colors.deepOrange[800],
              child: Icon(Icons.add_shopping_cart),
              onPressed: null);
        }
      }

It's not working, because condition work once, but state of orderList can be change anytime.

like image 860
Вячеслав Avatar asked Dec 13 '22 14:12

Вячеслав


1 Answers

You don't need to store the statusFAB variable, you can just evaluate it on the fly. See updated sample below:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: _getFAB(),
      backgroundColor: _kAppBackgroundColor,
      body: Builder(
        builder: _buildBody,
      ),
    );

  Widget _getFAB() {
    if (orderList.isEmpty) {
      return Container();
    } else {
      return FloatingActionButton(
          backgroundColor: Colors.deepOrange[800],
          child: Icon(Icons.add_shopping_cart),
          onPressed: null);
    }
  }
like image 194
Kirollos Morkos Avatar answered Feb 06 '23 21:02

Kirollos Morkos