Rakesh K
Rakesh K

Reputation: 8505

FutureBuilder vs initState in Flutter

I want to load some data from an SQLite database in my Flutter application and show the results in a ListView. I am currently using a FutureBuilder widget to fetch the data asynchronously from the database and then build the ListView.

However, if I want to do some operations on the data - e.g. modify some information and save it to database - and then show the updated data in the ListView, I think I have to store the data in a local variable first and then call the setState() method to make changes to the data and re-build the page.

Is there any other better/preferred way to achieve the same without using FutureBuilder?

Upvotes: 5

Views: 4207

Answers (2)

Gorges
Gorges

Reputation: 252

https://stackoverflow.com/a/52021385/11252673

build() might be called several times - that's why this kind of initialization goes better on initState.

Upvotes: 2

magicleon94
magicleon94

Reputation: 5172

initState gets called when your widget gets initialised for the first time. There you do some initialisation operations.

I think you're right to use FutureBuilder, since your UI gets generated after fetching the data from the Database.

I would do one of the following:

  • Keep using FutureBuilder, then when you edit the data make an async operation to update the database and after the database is updated call setState to reflect the changes on the UI.

  • Use a StreamBuilder, which is similar to FutureBuilder, but instead of building only once, it rebuilds each time there's a change on the stream it's attached to. This way you just need to update the datasource and the widget will update itself with the new data.

Talking about the second solution, I cannot go any further since I've never implemented a Stream that would allow to do this (I've always used StreamBuilder it with Firebase streams).

The first solution allows you to update the displayed data without asking again for the entire data set to the database.

I might appreciate some feedback from others regarding the second solution, since I'm not sure about how StreamBuilder manages a change of data.

I'll let you know if I discover more!

Upvotes: 5

Related Questions