如何从小部件中的Future <String>获取真实的字符串值?

时间:2019-12-23 19:35:10

标签: flutter

我在小部件中得到了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;
        }
    }
  }

如何从小部件中的Future中获得真正的价值?

3 个答案:

答案 0 :(得分:1)

使用 FutureBuilder()小部件来实现此目的。

将您的构建功能更改为关注

bad one
... %252F20191223%252Fsa-east-1%252Fs3%252Faws4_request& ...
good one
... %2F20191223%2Fsa-east-1%2Fs3%2Faws4_request& ...

答案 1 :(得分:0)

我认为您在调用(_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(''),

答案 2 :(得分:0)

您可以在initState()中调用方法并设置值,否则使用FutureBuilder处理未来值。您可以查看documentation of FutureBuilder