0
0
Fluttermobile~5 mins

Realtime Database in Flutter

Choose your learning style9 modes available
Introduction

A Realtime Database lets your app save and get data instantly. It keeps your app updated with changes right away, like chatting with friends or live scores.

You want to build a chat app where messages appear instantly.
You need to show live sports scores that update without refreshing.
You want to sync user settings across devices in real time.
You are making a collaborative to-do list app where everyone sees updates immediately.
You want to track delivery status live in a shopping app.
Syntax
Flutter
final database = FirebaseDatabase.instance.ref('path/to/data');
database.onValue.listen((event) {
  final data = event.snapshot.value;
  // Use data here
});
database.set({'key': 'value'});

FirebaseDatabase.instance.ref('path') gets a reference to a location in the database.

onValue.listen listens for any changes at that location in real time.

Examples
This listens to all changes under 'messages' and prints new data instantly.
Flutter
final ref = FirebaseDatabase.instance.ref('messages');
ref.onValue.listen((event) {
  print(event.snapshot.value);
});
This saves user data at 'users/user1' path.
Flutter
final ref = FirebaseDatabase.instance.ref('users/user1');
ref.set({'name': 'Alice', 'age': 25});
This listens to a number value and prints it whenever it changes.
Flutter
final ref = FirebaseDatabase.instance.ref('counter');
ref.onValue.listen((event) {
  final count = event.snapshot.value as int? ?? 0;
  print('Count is $count');
});
Sample App

This app shows a number from the Realtime Database. When you press the button, it adds 1 and updates the number everywhere instantly.

Flutter
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final DatabaseReference _counterRef = FirebaseDatabase.instance.ref('counter');
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _counterRef.onValue.listen((event) {
      final int newCount = (event.snapshot.value as int?) ?? 0;
      setState(() {
        _counter = newCount;
      });
    });
  }

  void _incrementCounter() {
    _counterRef.set(_counter + 1);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Realtime Counter')),
        body: Center(
          child: Text('Count: $_counter', style: TextStyle(fontSize: 32)),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          child: Icon(Icons.add),
          tooltip: 'Increment counter',
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always initialize Firebase before using Realtime Database.

Use onValue.listen to get live updates automatically.

Remember to handle null or missing data safely.

Summary

Realtime Database keeps your app data synced instantly.

Use database references to read and write data.

Listen to onValue stream to get live updates.