8

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.

Вячеслав
  • 707
  • 1
  • 12
  • 21
  • You need to call `setState()` on the parent widget to get `build` recalled. Please add more context to your code. Currently it's unclear what widget contains above code and why you expect the condition to be re-evaluated. – Günter Zöchbauer Sep 22 '18 at 16:25
  • https://gist.github.com/CoMatu/3d465d89553b57ea5e20c5996b10519a it is full code – Вячеслав Sep 22 '18 at 16:30
  • That code should be reduced to a minimal reproduction. The gist contains a lot of code that is entirely unrelated to the question and hardly anybody will want to spend the time to figure out what code is and is not related. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Günter Zöchbauer Sep 22 '18 at 16:36
  • I agree, so I showed the minimum code – Вячеслав Sep 22 '18 at 16:37
  • Can you show any abstract example, how possible show FAB on condition? – Вячеслав Sep 22 '18 at 16:40
  • It's not the minimum code because you stripped parts to the quesiton. Ideally the showed code should be fully runnable example (including `main() ...`). – Günter Zöchbauer Sep 22 '18 at 16:41
  • I can show full example only for you, but I dont know how make it – Вячеслав Sep 22 '18 at 16:42
  • Start with your running example (gist) and strip all code until it contains only what is essential to the question but still runnable and demonstrates the problem. Then add this remaining code to the question. – Günter Zöchbauer Sep 22 '18 at 16:46
  • As your are calling `setState`, you are having everything in Stateful widget. You dont need a separate variable for FAB state. You can directly use `orderList.isEmpty` itself. Whenever you have orderList from network/db, you should set orderList inside setState. – Dinesh Balasubramanian Sep 23 '18 at 03:07
  • You're right. It is StatefulWidget. Because I need to monitor the status of the list and show the FAB on the condition that the list is not empty – Вячеслав Sep 23 '18 at 11:59

3 Answers3

13

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);
    }
  }
Kirollos Morkos
  • 2,503
  • 16
  • 22
5

Well there is a shortcut which can be used with the ternary operator and can be used within Scaffold of a Stateful Widget as

floatingActionButton: orderList.isEmpty ? Container() : FloatingActionButton(...)

Unless you need a long and complicated function, this works fine. Even if you need a complicated function, then that function can be called only when the drawing was needed

floatingActionButton: orderList.isEmpty ? Container() : ComplicatedFn(...)

Widget ComplicatedFn() {
     //.... Complicated Algo
     return FloatingActionButton(...)
}
Daksh Gupta
  • 7,554
  • 2
  • 25
  • 36
0
import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Product> orderList = List();
  int counter = 0;

  void getCount(){
    setState(() {
      counter = orderList.length;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Center(
        child: Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              IconButton(
                onPressed: (){
                  if(orderList.isNotEmpty)
                  orderList.removeLast();
                  getCount();
                },
                icon: Icon(Icons.remove),
                color: Colors.red,
              ),
              Text('$counter'),
              IconButton(
                onPressed: (){
                  orderList.add(Product('product'));
                  getCount();
                  print('product added');
                },
                icon: Icon(Icons.add),
                color: Colors.blue,
              )
            ],
          ),
        ),
      ),
      floatingActionButton: _getFAB()
    );
  }

 Widget _getFAB() {
   if (orderList.isEmpty) {
     return Container();
   } else {
     return FloatingActionButton(
         backgroundColor: Colors.deepOrange[800],
         child: Icon(Icons.shopping_cart),
         onPressed: null);
   }  }
}

class Product {
  String title;
  Product(this.title);
}
Вячеслав
  • 707
  • 1
  • 12
  • 21