How to convert Future<List> to List in flutter?

Issue

I am using a plugin for flutter called search_widget.
The data parameter of this widget takes a list. But as I use sqlite for fetching data, I have it in Future<List> form.
Is there any way I can convert Future<List> to List?
Or any other way to get this working.

Solution

Borrowing the example from search_widget you need dataList in a widget like this:

SearchWidget<LeaderBoard>(
   dataList: list,
   textFieldBuilder: (TextEditingController controller, FocusNode focusNode) {
     return MyTextField(controller, focusNode);
   },
 )

Sure, you can convert Future<List> into List like other answers suggest. But you won’t be able to do dataList: await _sqliteCall(); because build methods are designed to be pure and sychronous.

While the Future completes you will have to return something like a progress indicator. For that you can use a FutureBuilder:

FutureBuilder<List<Leaderboard>>(
  future: _sqliteCall(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return SearchWidget<LeaderBoard>(
        dataList: snapshot.data,
        textFieldBuilder: (TextEditingController controller, FocusNode focusNode) {
          return MyTextField(controller, focusNode);
        },
      )
    }
    return CircularProgressIndicator();
  }
),

Of course this can also be done with a StatefulWidget, you can check this article for a detailed explanation of the issue.

Answered By – Frank Treacy

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.