0

I want to extract the future object from the http request so that I can use it as a regular object in the widget. How can I achieve this? (abstract code example below)

class _SomePageState extends State<SomePage> {
  Data? _data;

  @override
  void initState() {
    _loadData();
    super.initState();
  }

  void _loadData() async {
    await Service.getData().then((value) {
      setState(() {
        _data = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    //further use of the _data variable
  }
}

In this case i'll have lateInitialization Error. In general, I would like to hear brief recommendations for working with future objects with explanations. Thanks

  • Use a `FutureBuilder` – Ivo Jun 29 '22 at 13:09
  • The recommended thing is that the object that will be rendered is never a nullable one, that is, you have to have a default object with default values. You will change this object if your request is successful. – Chance Jun 29 '22 at 13:25

1 Answers1

0

Usually when working with Future's within the build method, we use FutureBuilder. Here is a video from the Google team on how to use it.

In your example:

In the _loadData() function:

Future _loadData() async {
  await data = Service.getData();
    return data;
}

In the build method

@override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
      style: Theme.of(context).textTheme.headline2!,
      textAlign: TextAlign.center,
      child: FutureBuilder<String>(
        future: _loadData(), 
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.hasData) {
            return Text("data exists");
          } else if (snapshot.hasError) {
            return Text(snapshot.error as String);

          } else {
            return CircularProgressIndicator();
          }
       
        },
      ),
    );
  }
MendelG
  • 14,885
  • 4
  • 25
  • 52
  • You could also .'then()' a future and setstate to update a state variable that comes from it, yeah? – aolsan Jun 29 '22 at 14:40
  • @aolsan you can use `then()` but here I'm using `async`/`await` which is a shorthand for `.then`. Also, since we're using Future Builder, you can update the variable there – MendelG Jun 29 '22 at 14:44