I have Boolean value in Firebase Realtime database i want a updated value without a screen Refresh in flutter. i want it to be updated streamline on flutter
CodePudding user response:
An easy way to handle your issue is to use "cloud_firestore" package. i'll make u a sample code below..
Note : Before using Firestore, you must first have ensured you have initialized FlutterFire! follow this link: https://firebase.flutter.dev/docs/overview/#initializing-flutterfire
import 'package:flutter/material.dart';
class TestWidget extends StatefulWidget {
const TestWidget({Key? key}) : super(key: key);
@override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
final Stream<QuerySnapshot> _usersStream =
Firebas`eFirestore.instance.collection('your collection name in database here').snapshots();`
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _usersStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const LinearProgressIndicator();
}
//this way you can extract your data from DB
//Of course it totally depend on if your data in Db is nested or not. just adjust it with your needs
return ListView(
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return Column(children: [
PassDataToAnotherWidget(data),
]);
}).toList(),
);
},
);
}
}
CodePudding user response:
If you have data in the Firebase Realtime Database, you can listen to update to that data through its onValue
stream. You can use this stream in your widget tree by using a StreamBuilder
:
@override
Widget build(BuildContext context) {
var ref = FirebaseDatabase.instance.ref('path_to_value');
return Scaffold(
StreamBuilder(
stream: ref.onValue,
builder: (context, snapshot) {
if (snapshot.hasData) return Text(snapshot.data!.snapshot.value);
if (!snapshot.hasData) return CircularProgressIndicator();
if (snapshot.hasError) return Text(snapshot.error);
}
)
)
I recommend watching this great code-along video: The Firebase Realtime Database and Flutter - Firecasts