Finno
Finno

Reputation: 147

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?

Upvotes: 5

Views: 25216

Answers (3)

aditya kontikal
aditya kontikal

Reputation: 82

Snapshot is just the response you may have from Firebase. So here they are just trying to check if the response is empty.

To access data from the received response, you can just do:

final responseData = snapshot.data

In fact you can also change the snapshot to any desired name you want.

Upvotes: 2

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12353

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).

Upvotes: 21

Randal Schwartz
Randal Schwartz

Reputation: 44056

Caution: there are two common meanings for snapshot. One is the one you use with StreamBuilder or FutureBuilder in the build method. The other is the kind of data you get back from Firebase. Unfortunately, you often use a Firebase snapshot in a FutureBuilder or StreamBuilder, which also uses the term snapshot, and the snapshot from Firebase ends up in the snapshot.data value in the builder at the appropriate time. Ugh!

Upvotes: 6

Related Questions