dart - 如何将future<>分配给flutter中的小部件?

假设我有一个SingleChildScrollView,它的内容是从一个文件中读取的:

singleChildScrollView(
        padding: EdgeInsets.all(8.0),
        child: nw Text(
          getTextFromFile(), //<---read from file
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 19.0,
          ),
        ));

  Future<String> getFileData(String path) async {
    return await rootBundle.loadString(path);
  }

  Future<String> getTextFromFile() async {
      return getFileData("test.txt");
  }

我收到以下错误:

The argument type 'Future<String>' can't be assigned to the parameter
type 'String'.

如何解决这个问题?

最佳答案

使用 FutureBuilder 应该可以解决您的问题。我修改了您的代码,以便您了解如何使用它。 initialData 不是必需的。

  @override
  Widget build(BuildContext context) {
    return new FutureBuilder(
      future: getTextFromFile(),
      initialData: "Loading text..",
      builder: (BuildContext context, AsyncSnapshot<String> text) {
        return new SingleChildScrollView(
          padding: new EdgeInsets.all(8.0),
          child: new Text(
            text.data,
            style: new TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 19.0,
            ),
          ));
      });
  }

  Future<String> getFileData(String path) async {
    return await new Future(() => "test text");
  }

  Future<String> getTextFromFile() async {
    return getFileData("test.txt");
  }
}

关于dart - 如何将future<>分配给flutter中的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49764905/

相关文章:

Flutter:删除按钮中的填充 - FlatButton、ElevatedButton、Outli

Flutter - 如何在 ListView 中居中小部件

flutter - 使连续的按钮在 flutter 中具有相同的宽度

api - 为 HTTPClient get() 请求设置超时

flutter - 找不到路线生成器

flutter - 如何在 Flutter 中获取当前选项卡索引

Flutter - 容器上的叠加卡片小部件

android - 使用 google dart 语言的原生移动应用程序

dart - 如何在 flutter 中将图像转换为base64图像?

dart - Flutter - 无法构建,因为框架已经在构建