如何转换Future< List>列出来?
我正在使用一个名为 search_widget
的插件。
此小部件的data参数带有一个列表。但是当我使用 sqlite
来获取数据时,我将其以 Future< List>
的形式保存。
有什么方法可以将 Future< List>
转换为 List
?
或任何其他使此工作正常进行的方法。
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.
从 search_widget ,您需要在这样的小部件中使用 dataList
:
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);
},
)
当然,您可以像其他答案一样将 Future< List>
转换为 List
。但是您无法能够执行 dataList:等待_sqliteCall();
,因为 build
这些方法的设计是纯净的和同步的。
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.
在未来完成时,您将必须返回诸如进度指示器之类的东西。为此,您可以使用 FutureBuilder
:
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();
}
),
当然也可以使用 StatefulWidget
完成,您可以检查有关此问题的详细说明,本文。
Of course this can also be done with a StatefulWidget
, you can check this article for a detailed explanation of the issue.