How to Use Future Return Value as if variable In Flutter ?

· 3 min read
How to Use Future Return Value as if variable In Flutter
How to Use Future Return Value as if variable In Flutter

At the time of fetching data from the backend on the launch page and if a user is using ListBuilder to get data to have two state variables First is data from backend and the Second is isLoadingFlag. In this article, we are going to discuss How to Use Future Return Value as if variable In Flutter?

What is FutureBuilder in Flutter?

FutureBuilder calls the future function to wait for the result, and as soon as it produces the result it calls the builder function where we build the widget.

How to Use Future Return Value as if variable In Flutter?

You can simply your function like the below:

Future<User> _fetchUserInfo(String id) async {
    User fetchedUser;
    var snapshot = await Firestore.instance
        .collection('user')
        .document(id)
        .get();
    return User(snapshot);
  }

You also need async/await to get the value.

void foo() async {
  final user = await _fetchUserInfo(id);
}

You can also use it like below:

var username;
dbHelper.getUsers().then((user) {
  username = user.getName;
});

this function returns the future value

dbHelper.getUsers()

It is written like this

getUsers() async { .... }

Let’s clarify using Futures in Flutter/Dart:

final user = _fetchUserInfo(id);

Without letting the compiler infer the type, that would be:

final Future<User> user = _fetchUserInfo(id);

Get & Use a Future Value

You can do this manually with a lot of boilerplate code, or you could use FutureBuilder.

FutureBuilder(future: user, builder: (context, snapshot) 
{
  if (snapshot.hasData) return Text(snapshot.data.userName);
  return Container(width: 0.0, height: 0.0,);
}

User can create a function like the below:

FutureBuilder<User>(future: user, builder: (context, AsyncSnapshot<User> userSnapshot)
{
  if (userSnapshot.hasData) return Text(userSnapshot.data.userName);
  return Container(width: 0.0, height: 0.0,);
}

Conclusion:

Thanks for Reading !!!

Keep Fluttering !!! Keep Learning !!!

Don’t forget to share your valuable Suggestions/Feedback for the same.

Still, need a Support For Flutter Development? Do let us know.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply