Franco Androetto
Franco Androetto

Reputation: 477

Why can't i refresh the build after init state

I am new to flutter and I encounter this problem that my Build does not refresh after a setState (). In my StatefulWidget I have to query a DB for a list of categories once I have that list of categories I have to display a ListView of the data. I pass my code to see if someone can give me a hand with a print of the varaible loading

class _ListCategoriesState extends State<ListCategories> {
  List<Category> _listCategories = new List();
  List<Article> _listArticles = new List();
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    doRequest();
  }
  void doRequest() async {
    getCategories().then((result) {
      setState(() {
        _listCategories = result;
        _loading = false;
      });
    }).catchError((error) {
      print(error);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: headerNav("Categorías"), body: _crearLista());
  }

  Widget _crearLista() {
    print(_loading);

    if (_loading) {
      return new Center(child: new CircularProgressIndicator());
    } else {
      return ListView.builder(
        itemCount: _listCategories.length,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text(_listCategories[index].description),
            trailing: Icon(Icons.keyboard_arrow_right),
          );
        },
      );
    }
  }

The print shows me true and then false

If someone can help me to understand also the concept that I have to use for this problem I have it in all the widget of my application.

Thanks!

Upvotes: 1

Views: 1423

Answers (1)

Kahou
Kahou

Reputation: 3488

Using FutureBuilder in the Scaffold body

body: FutureBuilder<List<Category>>(
       future: getCategories(),
       builder: (context, snap) {
         if (snap.data == null) {
           return Center(child: new CircularProgressIndicator());
         }

         return ListView.builder(/* ... */);
        },
      );

Upvotes: 2

Related Questions