[英]Using Flutter and Dart, how can I get this Future to work?
我知道還有其他方法可以實現此目的,但是我想通過initState()使用Future來使用SharedPreferences獲取列表。 以下內容說明了我想要實現的目標,但是它不能按要求工作,因為Future會在完成任務之前立即返回。
應該如何組織?
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class _MyHomePageState extends State<MyHomePage> {
SharedPreferences _prefs;
String _sMessage = "No response from getting params";
List<String> _lsCategories;
@override
void initState() {
super.initState();
_initPreferences().then((_) {
try {
_lsCategories = _prefs.getStringList("categories") ?? [];
debugPrint("Categories = $_lsCategories");
_sMessage = "Categories loaded OK";
} catch (vError) {
_sMessage = ("Error loading categories = $vError");
}
setState(() {});
});
}
Future<void> _initPreferences() async {
SharedPreferences.getInstance().then((prefs) {
_prefs = prefs;
debugPrint("Preferences initialized OK");
}).catchError((vError) {
debugPrint("Error initializing preferences = ${vError.toString()}");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_sMessage,
style: TextStyle(
color: Colors.red[500],
fontWeight: FontWeight.bold,
fontSize: 20)),
],
),
),
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Future Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: "Flutter Future Test"),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
將您的_initPreferences
方法更改為以下內容:
Future<void> _initPreferences() async {
try {
final prefs = await SharedPreferences.getInstance();
_prefs = prefs;
debugPrint("Preferences initialized OK");
} catch (e) {
debugPrint("Error initializing preferences = ${e.toString()}");
}
}
問題在於,在Future上使用.then()
時.then()
您不會等待該將來完成,而使用await
會等待。
試試吧。
Future<void> _initPreferences() async {
_prefs = await SharedPreferences.getInstance().catchError((vError) {
debugPrint("Error initializing preferences = ${vError.toString()}");
};
debugPrint("Preferences initialized OK");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.