RealTime Firebase Database
Introduction
Do you want to use the web to store the user’s data or to provide the common data for all the users? This post will help you out in storing user’s data on a web database, sending Http request(Store +Fetch), showing Loading Progress. This database provides us Realtime information, any device connected to the database can receive the updated data within milliseconds. This database can be accessed directly without an application server.
Table of contents:
1. Preparing our backend
We will use firebase as our dummy backend because it gives us a server where we do not need to write any server-side code to communicate with the database.
If you search for firebase flutter you will find out the official documentation on how to add firebase to your FLUTTER APP and they do through a firebase plugin. So if you want to use all the services provided by the firebase in your app you can go to this link.
Add Firebase to your Flutter app
Follow this guide to add Firebase products to a Flutter app. Firebase supports frameworks like Flutter on a best-effort…firebase.google.com
I don’t want to go into much detailing about firebase because this is not a firebase post therefore, we will use the generic part of firebase which you can easily replace with other backends. So particularly for this post, the important part for us is to understand the database where we can communicate through our app directly.
Sign in — Google Accounts
Edit descriptionconsole.firebase.google.com
The above list is the link of the firebase console. Please set up your project.
There are two types of database available cloud firestore and realtime database. We will be using a realtime database because it is easy to implement.
Please set test mode while setting up a realtime database because this ensures that anyone can read and write on the database.
2. Sending POST request
Package required
- import the http package file into your file and update your pubspec.yaml file.
dependencies:
http:
2. We have added as http to avoid naming clashes.
import 'package:http/http.dart' as http;
Generating request
To generate the post request we need the URL of our database which is available at the top of our database screen.
http.post("https://fir-flutted60b0.firebaseio.com/userprofile.json",
body: json.encode());
or
url =" https://fir-flutted60b0.firebaseio.com/userprofile.json";
http.post(url,body:json.encode());
Here we have also added “/userprofile.json” at the end of the URL. This is very important to add because the name “userprofile” is used as the field which is used to store the various attributes with a unique Id auto-generated by the firebase.
encode() statement is used to convert the data into JSON format.
Code Implementation:
sendData() {
http.post("https://fir-flutter-d60b0.firebaseio.com/userprofile.json",
body: json.encode({
'firstName': firstNameController.text,
'lastName': lastNameController.text,
'email': emailController.text,
}));
setState(() {
userProfile.add(Profile(
firstName: firstNameController.text,
lastName: lastNameController.text,
email: emailController.text,
));
});
}
Also at the time of sending a post request, we have to add the Profile Widget into our userProfile list.
I am using setState state management technique to manage the state of the list of the user profile which changes every time the user adds a new user.
Data stored in the DATABASE using post request looks like this ………
3. Sending GET request
To fetch the data we will again need the same URL.
final response = await http.get("https://fir-flutter-d60b0.firebaseio.com/userprofile.json?");
Here we have taken an empty list named loadedProfile which is a list of widgets that will be updated every time the user adds a new profile.
final List<Profile> loadedProfile = [];
We will the JSON data from the database, therefore, we will need to add a decode() statement.
NOTE: To use encode() and decode() statements we need to import
import 'dart:convert';
Here extractedData is a variable that will store the profile. Each element of the response needs to be converted into a widget to provide a responsive UI for the user, therefore we have used the forEach() and add() statement to identify every new profile and add Profile widget into the loadedProfile list
final extractedData = json.decode(response.body) as Map<String, dynamic>;
extractedData.forEach((profileId, profileData) {
loadedProfile.add(
Profile(
email: profileData['email'],
lastName: profileData['firstName'],
firstName: profileData['lastName'],
),
);
});
Data fetched from the DATABASE using get request…….
4. Preparing UI
- NewUser Widget
In this widget, we have three TextField() and a FlatButton() which will take add from the user and generate a get request when the FlatButton() is pressed.
Now we need three different controllers for all three TextField().
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
final emailController = TextEditingController();
Widget
TextField(
controller: firstNameController,
decoration:InputDecoration(labelText:'FirstName'),
),
TextField(
controller: lastNameController,
decoration: InputDecoration(labelText:'LastName'),
),
TextField(
controller: emailController,
decoration: InputDecoration(labelText: 'email'),
),
FlatButton(
child: Text("Send"),
color: Colors.indigo,
onPressed: sendData,
),
You can make a separate widget for this as well.
2. List of all the Users
This widget will show the list of all the users.
Profile() widget
https://gist.github.com/anmolseth06/2d2b17ae5d3822ac15f4424df969680d#file-profile-dart
I have used the ListTile() widget, you can change it if you don’t like it.
List Widget
Container(
child: Column(
children: userProfile
.map((ctx) => Profile(
firstName: ctx.firstName,
lastName: ctx.lastName,
email: ctx.email,
))
.toList(),
),
)
I have used the mapping method to create this widget because we don’t know the exact number of users available or uploaded by the app users.
userProfile is the list of all the users.
5. Showing Loading Progress
To show a CircularProgressIndicator() we need to initialize a new variable.
bool isloading = false;
The method sendData() needs to be converted into an async method and inside the method, we also need to initialize the await statement so that we can stop the execution of the further statement and by the time we can show the CircularProgressIndicator().
setting up the new sendData() method
Future<void> sendData() async {
setState(() {
isloading = true;
});
await http.post("https://fir-flutter-d60b0.firebaseio.com/userprofile.json",
body: json.encode({
'firstName': firstNameController.text,
'lastName': lastNameController.text,
'email': emailController.text,
}));
setState(() {
isloading = false;
});
setState(() {
userProfile.add(Profile(
firstName: firstNameController.text,
lastName: lastNameController.text,
email: emailController.text,
));
});
}
setting up the widgets
isloading?CircularProgressIndicator(): FlatButton(
child: Text("Send"),
color: Colors.indigo,
onPressed: sendData,
),
We are changing the FlatButton() to a CircularProgressIndicator().
6. Github link
flutter-devs/FirebaseRealTimeDatabase
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com
Thanks for reading this article ❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
If we got something wrong? Let me know in the comments. we would love to improve.
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.