問題描述
Flutter ‑ 迭代異步/未來列表 (Flutter ‑ iterate over an asynchrous/future list)
我正在嘗試使用 SharedPreferences 獲得的值創建一個列表。但是,如果我想使用 SharedPreference,我必須使用異步方法/未來類型,我不知道如何使用它們。我嘗試遍歷 sports
列表,但它是異步的/未來的。那麼我該如何迭代它(使用 map)?
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return MaterialApp(
Center(
child: Align(
alignment: Alignment.bottomCenter,
child: CarouselSlider(
options: CarouselOptions(
height: 565,
aspectRatio: 16/9,
enlargeCenterPage: true,
viewportFraction: .8,
),
items: sportsList.map((i) {
return Builder(builder: (BuildContext context) {
return Container(
.......
.........
.......
}
static Future<bool> initSharedPreference(String key) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(key) ?? false;
}
Future<List> sportsList() async {
List sports=[
await initSharedPreference("test")),
....,
....,
....
];
}
由於以下原因,此代碼不起作用:
未定義方法“map”對於“未來”類型。
參考解法
方法 1:
Why causing this problem?
Future<List> sportsList() async {
List sports=[
await initSharedPreference("test")),
....,
....,
....
];
}
The above code is not a simple list where the list can be directly rendered. It's returning Future<List>
which must be fetched as background work. So Use FutureBuilder
for it.
FutureBuilder is a one‑time call which will run only ones during its lifecycle. So you can rely on it.
FutureBuilder(
future: sportsList(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
} else {
List<Widget> list = snapshot.data;
return CarouselSlider(
options: CarouselOptions(
height: 565,
aspectRatio: 16/9,
enlargeCenterPage: true,
viewportFraction: .8,
),
items: list.map(.....).toList(),
);
}
})
方法 2:
Just use a FutureBuilder
widget.
In the following example, my asynchronous function is called getSportsList()
which returns a future List of Strings (This could be gotten from SharedPreferences, an API, et cetera. Just make sure it's a future).
class FutureList extends StatelessWidget {
@override
Widget build(BuildContext context) {
// THE FUTURE WIDGET
return FutureBuilder<List<String>>(
future: getSportsList(), // Add your asynchronous function here
builder: (context, AsyncSnapshot<List<String>> snapshot){
List<String> sports = snapshot.data;
// If there is no data in the snapshot, it is probably loading.
if(!snapshot.hasData) return CircularProgressIndicator();
// Now add the widget you want to return
else return CarouselSlider(
options: CarouselOptions(
height: 565,
aspectRatio: 16/9,
enlargeCenterPage: true,
viewportFraction: .8,
),
items: sportsList.map((String item) {
return Builder(builder: (BuildContext context) {
return Container(
.......
.........
.......
},
);
}
}
A snapshot basically gives info about the future. snapshot.data
is the result obtained from the future. snapshot.hasData
tells us whether the future returned a value or not, and there are a couple of other useful methods like snapshot.connectionState or snapshot.hasError for error handling.
For more resources, check out this video by the flutter team. Also check out the documentation to find out more
方法 3:
You need to use a FutureBuilder
like this..
FutureBuilder(
future: sportsList(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
} else {
return CarouselSlider(
items: snapshot.data.map(.....).toList(),
//other code
);
}
})
(by Jip Harthoorn、Jitesh Mohite、Wilson Wilson、Jigar Patel)