Search code examples
flutterdartsnapshot

What is a snapshot in Flutter?


I've been using a Firebase database in my project. I've been following a tutorial, and when returning widgets to the future builder it says to use:

if(snapshot.hasError) {
    // Cannot connect to database
}
else {
    // Return widgets as normal
}

I have checked the Flutter documentation and they say a snapshot is:

Immutable representation of the most recent interaction with an asynchronous computation.

But what does this mean, and why does the above code make sense?


Solution

  • Snapshot is the result of the Future or Stream you are listening to in your FutureBuilder.

    Before interacting with the data being returned and using it in your builder, you have to access it first.

    To access this data, which is technically being delivered indirectly to you, by your FutureBuilder, you need to ask FutureBuilder for it.

    You do this by first, saying snapshot, because that is the nickname so to speak you told Flutter that you will be using, because your Future builder looks something like this:

     FutureBuilder(
         future: someFutureFunction(),
         builder: (context, snapshot) { // Here you told Flutter to use the word "snapshot".
         if (snapshot.connectionState == ConnectionState.waiting)
             return Center(child: CircularProgressIndicator());
         else
             return Text(counter.toString());
    }),
    

    If you refereed to it as "finno", you can later on access this information by typing finno.data.

    snapshot has many properties you can make use of, like hasData and connectionStatus.

    If your future was expected to return an object you created, for example

    Student(String name, int age)
    

    You can print the name by saying print(snapshot.data.name).