Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign future<> to widget in flutter?

Tags:

flutter

dart

Suppose I have a SingleChildScrollView, its content is read from a file:

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");
  }

I got the following error:

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

How to solve the issue?

like image 887
camino Avatar asked Sep 01 '25 04:09

camino


1 Answers

Using a FutureBuilder should solve your problem. I modified you code so you can see how to use it. initialData is not required.

  @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");
  }
}
like image 60
Doge Avatar answered Sep 02 '25 17:09

Doge