I'm trying figured out how to work with future for fetching data over internet. I was trying to write a simple code where I convert Future into "average" data but it doesn't work and I can't get why that's happend.

Here's my code

class Fetch {  
  Data getData () {
    Data data;
    data = fetch().then((value) {data = value;}); //here's I'm getting error
  }

  Future<Data> fetch() async {
    int number = await Future.delayed(Duration(seconds: 1), () => 3);
    return(Data.fromIt(number));
  }
}

class Data{
  int date;

  Data({this.date});

  factory Data.fromIt(int num) {
    return Data(
      date: num,
    );
  }
}

After I corrected this part of code error has gone but now getData() returns null instead of value:

Data getData () {
  Data data;
  fetch().then((value) {data = value;});
  return data; //null
}

Thanks


Solution 1: bentesha

You can make getData an async function, and use the await keyword. It is much easier to understand if you are new to async programming and Futures

Future<Data> getData () async {
    final data = await fetch();
    // Whatever you want to do with data
    return data; // Dont forget to return it back to the caller
  }


Solution 2: Bach

The data is defined as a Data object, while fetch() returns a Future<Data>, causing the error.

Data data;
  data = fetch().then((value) {
    data = value;
  }); 

You can not transform a Future object to a synchronous object without awaiting it. You can do this at the UI to get the Future value:

FutureBuilder<Data>(
  future: Fetch().fetch(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return Container();
    Data data = snapshot.data;
    return Text(data);
  },
)