how to assign future<> to widget in flutter?

Simple answer here=>

The class which calls the function:

@override
Widget build(BuildContext context) {
return new Scaffold(
 child: FutureBuilder(
  future: function(),
  builder: (BuildContext context, AsyncSnapshot<String> text) {
    return new Text(text.data);
  });
)}

And the function:

Future<String> function() async {
   return 'abc';
}

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

StatefulWidget can be used for this purpose. Declare a member variable String _textFromFile = ""; in your State class and update its value on future resolve by using setState() method.

I called your getTextFromFile() method from the constructor, but you may call it from anywhere.

Running code:

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

Here's a similar question:

flutter / dart error: The argument type 'Future<File>' can't be assigned to the parameter type 'File'

The solution proposed there is quite elegant and works properly. Where the IDE says it's expecting Type and not Future<Type>, put await in front of that argument

Tags:

Dart

Flutter