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

2024-01-16

假设我有一个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");
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 future<> 分配给 flutter 中的小部件? 的相关文章

随机推荐