class _WorterBuchState extends State<WorterBuch> with TickerProviderStateMixin {
var wordPair= '' ;
@override
void initState(){
super.initState();
load();
}
Future<void> load() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('key', 'value');
wordPair = await "key : " + (prefs.getString('key') as String);
}
@override
Widget build(BuildContext context) {
print(wordPair);
我有这个类和这个异步函数。我在 initState 调用中运行异步函数,但是当构建方法运行时它什么也不打印。我怎样才能解决这个问题或者我怎样才能等待未来如何完成?有人可以帮忙吗
Future 方法需要一些帧来获取数据,尝试使用 FutureBuilder 像
Future<String> load() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('key', 'value');
final wordPair = "key: ${prefs.getString('key')}";
return wordPair;
}
late final future = load();
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: future,
builder: (context, snapshot) {
if (snapshot.hasData) {
final wordPair = snapshot.data ;
return Text(wordPair??'');
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
);
}
}
更多关于FutureBuilder
无法延迟运行
build
方法,并且此方法不能异步,因为这会阻止/延迟 UI 的渲染,从而使应用程序无响应。
您需要做的是将
Future
存储在状态中并使用 FutureBuilder
:
class _WorterBuchState extends State<WorterBuch> with TickerProviderStateMixin {
Future<String>? wordPairFuture;
@override
void initState(){
super.initState();
load();
}
Future<void> load() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('key', 'value');
wordPairFuture = "key : " + (prefs.getString('key') as String);
}
@override
Widget build(BuildContext context) {
if (wordPairFuture == null) {
return const Placeholder(); // display some loading here
}
return FutureBuilder(
future: wordPairFuture,
builder: (context, snapshot) {
// use `snapshot.hasData` to check if the `Future` is "ready"
if (snapshot.hasData) print(snapshot.data)
// ...
}
)