Flutter - Realtime Database in Firebase - GeeksforGeeks

23 Jun, 2021
Firebase helps developers to build and run their apps successfully, its backend developed by Google. Firebase is very easy to use for beginners, it provides many functionalities like Firebase Authentication, Cloud Firestore, Realtime Database, Firebase Storage, etc which help to build and optimize the application. In this article, we will learn about how to use Firebase Realtime Database to read and write data in Flutter. This process includes three steps:
Firebase SetupAdd Realtime Database to applicationImplementation to read and write
Firebase Setup
Add Realtime Database to application
Implementation to read and write
Step 1: Open Firebase-Google in our browser then click on ‘Go to console’ in the top rightmost corner of the page (Make sure that we must log in through our Google account in firebase) and then click on ‘Add project’.
Step 2: Give a name to our project and click ‘Continue’.
Step 3: After successfully creating the project, this screen will appear and there will be a lot of options on the left side of the page provided by firebase and then Select the Realtime Database option among these.
Step 4: Press the ‘Create Database’ button and then Select any location or keep it as it is and then click to ‘next’ and Select the test mode option which gives access to read and write data in the database and Press ‘enable’.
After that Firebase Realtime Database setup is done successfully.
Copy the Database URL from Firebase Realtime Database in the green box shown below and replace the URL with DatabaseURL in writeData() and readData() function in Add Data and Read Data code :
Step 1: Add HTTP package in the pubspec.yaml under dependencies in flutter project:
dependencies:
  flutter:
     sdk: flutter
  http: ^0.13.3  
Save the above file.
Note: Please make sure that while adding the above code, it must be the same level as flutter.
After saving the file, if any error occurs then check the spacing of code with flutter and also check that you have added the correct version of the HTTP package.
Step 2: Add Data.
Dart
import 'package:flutter/material.dart';import 'package:http/http.dart' as http;import 'dart:convert';  void main() {  runApp(MyApp());}  class MyApp extends StatefulWidget {  @override  _MyAppState createState() => _MyAppState();}  class _MyAppState extends State<MyApp> {  final _form = GlobalKey<FormState>();  String title;  void writeData() async {    _form.currentState.save();          // Please replace the Database URL    // which we will get in “Add Realtime    // Database” step with DatabaseURL    var url = "DatabaseURL"+"data.json";          // (Do not remove “data.json”,keep it as it is)    try {      final response = await http.post(        Uri.parse(url),        body: json.encode({"title": title}),      );    } catch (error) {      throw error;    }  }    @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'RealTime Database',      theme: ThemeData(        primarySwatch: Colors.green,      ),      home: Scaffold(        appBar: AppBar(          title: Text("GeeksforGeeks"),        ),        body: Form(          key: _form,          child: Center(            child: Column(              children: [                SizedBox(                  height: 10,                ),                TextFormField(                  decoration: InputDecoration(hintText: "Enter Title"),                  onSaved: (value) {                    title = value;                  },                ),                SizedBox(                  height: 10,                ),                RaisedButton(                    onPressed: writeData,                    color: Colors.green,                    child: Text(                      "Submit",                      style: TextStyle(color: Colors.white),                      textAlign: TextAlign.center,                    )),              ],            ),          ),        ),      ),    );  }}
Note: Please replace the Database URL which we will get in the “Add Realtime Database to application” step with DatabaseURL in the writeData() function.
Output:
Realtime Database:
Explanation: In the above code, we have created a textformfield and submit button. TextformField to get title data from user and submit button to call a function which writes data in firebase i.e key-value pair of “title”- user input is pushed into a realtime database. If Button is pressed multiple times then Data is stored repeatedly.
Step 3: Read Data.
Dart
import 'package:flutter/material.dart';import 'package:http/http.dart' as http;import 'dart:convert';  void main() {  runApp(MyApp());}  class MyApp extends StatefulWidget {  @override  _MyAppState createState() => _MyAppState();}  class _MyAppState extends State<MyApp> {  void initState() {    super.initState();    readData();  }    bool isLoading = true;  List<String> list = [];  Future<void> readData() async {          // Please replace the Database URL    // which we will get in “Add Realtime Database”     // step with DatabaseURL          var url = "DatabaseURL"+"data.json";    // Do not remove “data.json”,keep it as it is    try {      final response = await http.get(Uri.parse(url));      final extractedData = json.decode(response.body) as Map<String, dynamic>;      if (extractedData == null) {        return;      }      extractedData.forEach((blogId, blogData) {        list.add(blogData["title"]);      });      setState(() {        isLoading = false;      });    } catch (error) {      throw error;    }  }    @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'RealTime Database',      theme: ThemeData(        primarySwatch: Colors.green,      ),      home: Scaffold(          appBar: AppBar(            title: Text("GeeksforGeeks"),          ),          body: isLoading              ? CircularProgressIndicator()              : ListView.builder(                  padding: const EdgeInsets.all(8),                  itemCount: list.length,                  itemBuilder: (BuildContext context, int index) {                    return Container(                        height: 50,                        child: Center(                          child: Text(                            list[index],                            style: TextStyle(color: Colors.green),                          ),                        ));                  })),    );  }}
Note: Please replace the Database URL which we will get in the “Add Realtime Database to application” step with DatabaseURL in readData() function.
Output:
Realtime Database:
Explanation: In the above code, we create CircularProgressIndicator which will rotate until we fetch data from the firebase database and when we get data, it will show the list of data which we are in firebase in listview builder widget with green colored text data.
android
Firebase
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Services in Android with Example
Content Providers in Android with Example
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar