flutterasynchronousasync-awaitflutter-futurebuilder

How can I use async data in a FutureBuilder in Flutter?


I'm new to Flutter and trying to load data from Firestore and then use the data in my FutureBuilder. I have to load the data before I can build the UI because how I build it depends on the data.

So I get the data with an async function I wrote called .getUserfromFirestore, which returns an AppUser object containing all my data mapped from the Firestore data. I confirmed with debug prints that the AppUser has all the data.

But the object I get back is considered a Future version of the object instead of the actual object with its data. So when I try to debugPrint(${appUser.currentTimeline}), for example, I get the error:

The getter 'currentTimeline' isn't defined for the type Future<AppUser>

How can I access the actual AppUser object returned from my async function?

Here is my code:

class _HomePageState extends State<HomePage> {

  late Future<AppUser?> appUser; //appUser is an object with many parameters.

  @override
  initState() {
    super.initState();
    // this gets the data and makes an appUser object
    appUser = UserService().getUserfromFirestore(); 
  }

  // This is the basic structure of the page.
  @override
  Widget build(BuildContext context) {
       return FutureBuilder( // Using a FutureBuilder here because we have to wait to pull the user data from Firestore...
        future: appUser, // Must wait for appUser to proceed with the build...
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            debugPrint("The AsyncSnapshot has data.");
            debugPrint('${appUser.currentTimeline}');
          }
          return ColorfulSafeArea( <this builds the UI>)
}

Solution

  • The data is in snapshot. Try looking at snapshot.data.currentTimeline.