Firebase Realtime Database Flutter

Store and sync data with our NoSQL cloud database. Data is synced across all clients in realtime, and remains available when your app goes offline.

The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our Apple platforms, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data.

How does it work?

The Firebase Realtime Database lets you build rich, collaborative applications by allowing secure access to the database directly from client-side code. Data is persisted locally, and even while offline, realtime events continue to fire, giving the end user a responsive experience. When the device regains connection, the Realtime Database synchronizes the local data changes with the remote updates that occurred while the client was offline, merging any conflicts automatically.

The Realtime Database provides a flexible, expression-based rules language, called Firebase Realtime Database Security Rules, to define how your data should be structured and when data can be read from or written to. When integrated with Firebase Authentication, developers can define who has access to what data, and how they can access it.

The Realtime Database is a NoSQL database and as such has different optimizations and functionality compared to a relational database. The Realtime Database API is designed to only allow operations that can be executed quickly. This enables you to build a great realtime experience that can serve millions of users without compromising on responsiveness. Because of this, it is important to think about how users need to access your data and then structure it accordingly.

CRUD Operation

DatabaseReference ref = FirebaseDatabase.instance.ref();
Dart

Insert Data:-

This document covers the basics of reading and writing Firebase data.

Firebase data is written to a DatabaseReference and retrieved by awaiting or listening for events emitted by the reference. Events are emitted once for the initial state of the data and again anytime the data changes.

Using set() in this way overwrites data at the specified location, including any child nodes. However, you can still update a child without rewriting the entire object. If you want to allow users to update their profiles you could update the username as follows:

INSERT DATA

vardata={'id':id.text,'fname':name.text,'lname':lastname.text };//set method use to insert new recordawaitdatabase!.child(id.text).set(data);
Dart

Update Data:

The 

update() method accepts a sub-path to nodes, allowing you to update multiple nodes on the database at once:

var data={
    'id':id.text,
    'fname':name.text,
    'lname':lastname.text
 };
 //update method use to update record
await database!.child(id.text).update(data);
Dart

Delete data:

The simplest way to delete data is to call remove() on a reference to the location of that data.

DELETE DATA

//remove method delete that record in 
childawaitdatabase!.child(id.text).remove();
Dart

Copy

List Data:

To read data at a path and listen for changes, use the onValue property of DatabaseReference to listen for DatabaseEvents.

You can use the DatabaseEvent to read the data at a given path, as it exists at the time of the event. This event is triggered once when the listener is attached and again every time the data, including any children, changes. The event has a snapshot property containing all data at that location, including child data. If there is no data, the snapshot’s exists property will be false and its value property will be null.

LIST DATA

void calldatatview() {

    database!.onValue.listen((event) {
      var data=event.snapshot.value as List;
      setState(() {
        userList.clear();
        data.forEach((element) {
          if(element!=null){
            userList.add(UserData(element['id'], element['fname'], element['lname']));

          }
          });
      });
    });
  }

class UserData{
  String? id;
  String? fname;
  String? lname;
  UserData(this.id, this.fname, this.lname);
}
Dart

FULL CODE:

import 'dart:convert';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class RealtimeData extends StatefulWidget{
  @override
  State<StatefulWidget> createState()=>RealtimeDataState();

}

class RealtimeDataState extends State<RealtimeData> {
  var name=TextEditingController();
  var id=TextEditingController();
  var lastname=TextEditingController();
  List<UserData> userList=[];
  //databASE OBJECT
  late DatabaseReference? database;
  @override
  void initState()   {
    // TODO: implement initState
    super.initState();
    setState(() {
      database=FirebaseDatabase.instance.ref("Users");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Firebase CRUD"),),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            SizedBox(height: 100,),
            TextField(
              decoration: InputDecoration(
                  hintText: "Enter Id"
              ),
              controller: id,
            ),
            SizedBox(height: 20,),
            TextField(
              decoration: InputDecoration(
                hintText: "Enter Name"
              ),
              controller: name,

            ),
            SizedBox(height: 20,),
            TextField(
              decoration: InputDecoration(
                  hintText: "Enter LAST NAME"
              ),
              controller: lastname,
            ),
            SizedBox(height: 20,),
            Row(
              children: [
                ElevatedButton(onPressed: () async {
                    var data={
                      'id':id.text,
                      'fname':name.text,
                      'lname':lastname.text
                    };
                    //set method use to insert new record
                    await database!.child(id.text).set(data);

                }, child: Text("INSERT")),
                Spacer(),
                ElevatedButton(onPressed: () async {
                  calldatatview();

                }, child: Text("View")),
                Spacer(),
                ElevatedButton(onPressed: ()async{
                  var data={
                    'id':id.text,
                    'fname':name.text,
                    'lname':lastname.text
                  };
                  //update method use to update record
                  await database!.child(id.text).update(data);
                }, child: Text("UPDATE")),
                Spacer(),
                ElevatedButton(onPressed: ()async{
                  //remove method delete that record in child
                  await database!.child(id.text).remove();
                }, child: Text("DELETE")),

              ],
            ),
            SizedBox(height: 20,),
              //dispay list of data
            Expanded(child:
            ListView.builder(
              itemCount: userList.length,
              itemBuilder: (BuildContext context, int index) {
                return GestureDetector(
                  child: ListTile(
                    title: Text("${userList[index].id}"),
                    subtitle: Text("${userList[index].fname} ${userList[index].lname}"),
                  ),
                  onTap: (){
                    setState(() {
                      id.text=userList[index].id.toString();
                      name.text=userList[index].fname!.toString();
                      lastname.text=userList[index].lname.toString();
                    });
                  },
                );
              },

            )
            )
          ],
        ),
      ),
    );
  }

  void calldatatview() {

    database!.onValue.listen((event) {
      var data=event.snapshot.value as List;
      setState(() {
        userList.clear();
        data.forEach((element) {
          if(element!=null){
            userList.add(UserData(element['id'], element['fname'], element['lname']));

          }
          });
      });
    });
  }


}
class UserData{
  String? id;
  String? fname;
  String? lname;
  UserData(this.id, this.fname, this.lname);
}
Dart