How to I take the return statement of a future and put it in a widget?

Viewed 39

I have been trying to add the return statement of a Future in a Widget. Here is my Future code:

Future<Widget> readName() async {
  try {
    final file = await _localNames;

    // Read the file
    String contents = await file.readAsString();
    return Text('Assignment' + contents);
  } catch (e) {
    // If encountering an error, return 0
    return Text('Error');
  }
}

This is my widget:

Widget build(BuildContext ctxt) {
  return MaterialApp(
    home: Scaffold(
      appBar: new AppBar(
        title: new Text("My assignments"),
      ),
      body: Container(
        margin: const EdgeInsets.only(top: 10.0),
        child: Align(
          alignment: Alignment(0, -0.9),
          child: Column(
            children: <Widget>[
              // Need Text Here                
            ],
          ),
        ),
      ),
    ),
  );
}

How do you solve this? I have been trying to find out the solution for a day. Thanks for your time!

1 Answers

You can use FutureBuilder to get data from Future and use it however you want;

FutureBuilder according to the documentationis:

Widget that builds itself based on the latest snapshot of interaction with a Future

This code below works fine with the use of FutureBuilder:

Widget build(BuildContext ctxt) {
  return MaterialApp(
    home: Scaffold(
      appBar: new AppBar(
        title: new Text("My assignments"),
      ),
      body: Container(
        margin: const EdgeInsets.only(top: 10.0),
        child: Align(
          alignment: Alignment(0, -0.9),
          child: Column(
            children: <Widget>[
              // Need Text Here
              FutureBuilder<Widget>(
                future: readName(),
                builder: (context, snapshot) {
                  if (snapshot.hasData)
                    return snapshot.data;
                  return Center(child: CircularProgressIndicator());
                }
              ),
            ],
          ),
        ),
      ),
    ),
  );
}

To read more about FutureBuilder. Check the link below: FutureBuilder

Related