小编典典

如何在Flutter中将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'.

该如何解决呢?


阅读 454

收藏
2020-08-13

共1个答案

小编典典

StatefulWidget可用于此目的。声明一个成员变量String _textFromFile = "";
在您的State类中,并通过使用setState()method
在将来解决时更新其值。

getTextFromFile()从构造函数调用了您的方法,但是您可以在任何地方调用它。

运行代码:

import 'package:flutter/material.dart';
import 'dart:async';

class StatefullWidgetDemo extends StatefulWidget {
  @override
  _StatefulWidgetDemoState createState() {
    return new _StatefulWidgetDemoState();
  }
}

class _StatefulWidgetDemoState extends State<StatefullWidgetDemo> {
  String _textFromFile = "";

  _StatefulWidgetDemoState() {
    getTextFromFile().then((val) => setState(() {
          _textFromFile = val;
        }));
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Stateful Demo'),
      ),
      body: new SingleChildScrollView(
        padding: new EdgeInsets.all(8.0),
        child: new Text(
          _textFromFile,
          style: new TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 19.0,
          ),
        ),
      ),
    );
  }

  Future<String> getFileData(String path) async {
    return "your data from file";
  }

  Future<String> getTextFromFile() async {
    return await getFileData("test.txt");
  }
}
2020-08-13