这可能是一个愚蠢的问题,但我的问题是,我有一个未来的返回值,我想为其分配一个变量,但该变量仅在“代码块”中保持不变
我想同步返回值
bool getDarkMode() {
bool testBool;
test().then((myBool) {
testBool = myBool;
});
return testBool;
}
我想返回testBool变量的值。
Future<bool> getDarkMode() async {
bool testBool = await test();
return testBool;
}
或者您可以消除testBool并使用
Future<bool> getDarkMode() async{
return await test();
}
使用then暗示,它test()返回一个未来。这意味着您不能以同步方式使用它。(假设test有以下签名:Future<bool> test() { ... }
您需要getDarkMode通过 async 使您的函数像这样:
Future<bool> getDarkMode() {
return test();
}
或者如果您需要处理以下结果test:
Future<bool> getDarkMode() async {
bool res = await test();
return res;
}
没有办法将异步值“转换”为同步值。
如果您在小部件的构建方法中需要此值,则可以使用FutureBuilder:
Widget build(BuildContext context) {
return FutureBuilder<bool>(
future: getDarkMode(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Text('Loading...');
}
final darkMode = snapshot.data;
return Text(darkMode ? 'DARK' : 'LIGHT');
},
);
}