This app shows a number from the Realtime Database. When you press the button, it adds 1 and updates the number everywhere instantly.
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',
),
),
);
}
}