与预期的字符串值不同,我在小部件中得到了Instance of Future<String>:(在winget的第二行中,字符串值应该是373,8)
(_rapport.isNotEmpty && _rapport.length == 3)
? Text((_distortion(_rapport, widget.printer)).toString()) // this function return Future<String>
: const Text(''), // rapport is empty其职能是:
Future<String> _distortion(String rapport, String printer) async {
final String record = await _getRecord(rapport);
print('record: ${record.toString()}'); // this gives me an expected valid output
final List row = record.toString().split(';');
final String d1 = row[1]; // tachys
final String d2 = row[3]; // onyx
switch (printer) {
case 'Tachys':
{
print('distortion: $d1'); // output: distortion: 373,8
return d1;
}
break;
default:
{
print('distortion: $d2');
return d2;
}
}
}我如何从未来的小部件中获得真正的价值?
发布于 2019-12-23 20:25:19
这样做的方法是使用FutureBuilder()小部件。
将构建函数更改为
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future : _distortion()
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading....');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return (_rapport.isNotEmpty && _rapport.length == 3)
? Text(snapshot.data)
: (_rapport.isNotEmpty && _rapport.length < 3)
? const Text('wrong rapport')
: const Text(''), // rapport is empty
);
}
},
),
);
}发布于 2019-12-23 19:46:24
我认为在调用(_distortion)函数时必须添加异步等待,如下所示:
(_rapport.isNotEmpty && _rapport.length == 3)
? Text(await (_distortion(_rapport, widget.printer)).toString()) // this function return Future<String>
: (_rapport.isNotEmpty && _rapport.length < 3)
? const Text('wrong rapport')
: const Text(''),发布于 2019-12-24 07:39:00
可以在initState()中调用方法并设置值,否则使用FutureBuilder来处理未来的value.You可以查看FutureBuilder文档
https://stackoverflow.com/questions/59460460
复制相似问题