Firebase Database in Flutter – WeightTracker 3
In this post, I’m going to go through adding Firebase Database to a Flutter application. The presented development is part of my Weight Tracker app (simple app for tracking weight), so the development will be based on that and focused on that purpose.
Let’s get to it!
Setting up Firebase
The first thing we need to do is set up Firebase integration. It is clearly explained in Firebase’s Codelab, so before moving on I would recommend you going through point 5 in order to connect to Firebase.
For this course we are not going to use Authentication, however, the default rules for Firebase Database require users to be authenticated. To change that we will modify database’s rules file to allow anyone to read and write to the database:
After we set everything up, all we need is to add firebase dependency to our flutter project’s pubspec.yaml
file
and we are ready to go!
. . .
Pushing data to database
Firebase database plugin is very simple to use. To get main reference of our application all we need to do is get access to static field in FirebaseDatabase class.
If we would like to get into more specific child of our database, we can simply call mainReference.child(“name_of_child”).
To push an object into database we can just call push and set methods on reference object.
However, the set method doesn’t accept just an object. It needs to be a dynamic value already in a json-map format. In order to transform our object to the format we want, I added toJson method:
Now we can call
And we end up with an entry stored in our database.
. . .
Reading data form database
In order to get data from the database, we add a listener to the reference we are interested in (in that case it will be mainReference). Once we get the value, we will simply add it to the state’s list and call setState method.
Side note: I present only getting value from database and adding it to the local list. If you are interested in how to display it, check out my GitHub repository for full code. The link provided at the end of the post.
As you can see, database listener consumes Event object. The actual object we are interested in is in event.snapshot.value. However, it is the same dynamic format we have pushed. In order to parse it to WeightEntry, I added constructor accepting DataSnapshot and then getting specific fields from value. I also added Key to the class, which is the unique value Firebase is creating on push. It will be needed in editing.
. . .
Updating data
Since we added Key to the WeightEntry model, it is very easy to update a value in the database.
Code below shows how to edit value in database once we have the object we want to pass:
Calling child(key) will return a reference to the object we want to edit, then setting new value will make a deal. This action will result in an updated entry in the database, however, our application won’t notice it. In order to stay updated with data edits, we need to add a change listener.
Now on every child changed in mainReference, we update this child in our local listView and call setState.
BONUS: If you want your application to store data in local memory in case of no network connection, this is the way
End notes
Wiring up Flutter application with Firebase is very easy and straight forward. I strongly encourage everyone to try it out. In the near future, I will go through Firebase Authentication for more complex usage of Firebase (link will be provided). If you are interested in more Flutter-Firebase content, you can see the Codelab I talked about earlier. You can also check out firebase_database plugin itself.
I hope you liked that post, I would be grateful for any feedback so please feel free to leave a comment
That’s it, folks!
You can find the whole project here. (You need to create own google-services.json to connect to Firebase)
Marcin Szałek
Founder of Fidev
Flutter enthusiast since Alpha release in 2017. Believes that sharing is caring, which lead him to start a technical blog dedicated fo Flutter in its early days. Loves to see beautiful designs become real apps and is willing to help make it happen. Enjoys sunny beaches far from home.
Join the newsletter!
Join the newsletter to keep track with latest posts and get my special Widget to animate views' entrances without any hassle for FREE!
Check out other posts!
Stripe Checkout in Flutter Web
Flutter Web is getting more mature every day. If you want to accept payments using Stripe Checkout in your Flutter web application, this article is just for you!
Stripe Checkout in mobile Flutter app
Have you ever struggled to integrate card payments into your mobile Flutter app? If so, today is your lucky day! In this post, I present how to use Stripe Checkout in the Flutter app without any hassle!
Interacting with Widgets using Framy
Have you ever developed a widget or a page and you wanted to make sure it works correctly in different scenarios but then it turned out that you can’t just reproduce all the cases you want to cover? Framy may solve such problems!
Cool post, thanks for sharing!
My pleasure 😉
Nice, this is what i`ve been looking for 😉
Nice tutorial! Do you have also an example populating data on text fields using data from database?
What do you mean exactly?
What I mean is… with Step 3. you are reading data from Firebase Realtime database right? can you also include an example in which, after you have read the data from the database, you will use the data to pre-populate the form fields (like weight text field, etc..)
Once I get data from Firebase I count it as normal data I would have in local memory. You can check out my repository to see how everything is wired up 🙂
https://github.com/MSzalek-Mobile/weight_tracker/tree/v0.3
Cool post!
I have problems with the WEIGHTTRACKER, flutter not found import ‘package:intl/intl.dart’;
What can i do?
Sorry for my english
Hi!
Error is probably caused by Flutter updates made since publication of this post. If you use most recent version of app (https://github.com/MSzalek-Mobile/weight_tracker) it should work well.
If you want to use version linked in the post try adding missing import in pubspec.yaml. I think that in that case dates may not display correctly (because of changes in Flutter).
Let me know how it goes 🙂
Thank you for the reply, i could make it works. It was the missing depency in the pubspec. Im going to try the last version too.
Thanks!
I have an other question: Do you have any example of using firebase cloud store in flutter?
Regards,
No, but if you mean FirebaseStorage, then this (https://codelabs.developers.google.com/codelabs/flutter-firebase/#9) might be helpful 🙂
Hi man! Great use case.
Say me how to get / setting / generate key.properties file? I’m newbie on Firebase.
Can you help me?
Error:
FAILURE: Build failed with an exception.
* Where:
Build file ‘C:\Projetos\weight_tracker\android\app\build.gradle’ line: 21
* What went wrong:
A problem occurred evaluating project ‘:app’.
> C:\Projetos\weight_tracker\android\key.properties (O sistema não pode encontrar o arquivo especificado)
Great one – I cant find a lot (useful stuff) about flutter with firebase on youtube so I started searching the web. Now I finally found something that actually works!
How to handle relational data like
{
“weight”: weight,
“date”: dateTime.millisecondsSinceEpoch,
“invoice line”: {
“name”: “Product 1”,
“price_unit”: 111
{
“name”: “Product 2”,
“price_unit”: 222 }
}
}
Hey,
this highly depends on nature of your app.
One solution would be to ditch listening for updates for just one time requests where you could download all neede data in one async function. You could also download list of all products and have them as a dictionary in memory (it would obviously depend on size of the list). Other way would be to add database listener for every product you need in invoice line. I hope it helps somehow… Please tell me how you handled it 😉
Sir, how to add images upload and profile set ????
Thanks, really great tutorial. But i encounter problem,
Why i cant login in your app?
In settings > Continue with Google > Choose my Google Account
> then nothings happen..
okay i resolve it, i need to enable authentication first. Thanks
Hi Rizal, actually I did this feature but I haven’t tested nor publish it yet.
Actually, I would be very grateful if you could confirm that this is working after setting up your own Firebase Auth. 🙂