我在Firebase实时数据库中有布尔值,我想要一个更新的值,而不需要在扑动中刷新屏幕。我希望它是更新流线上的扑动
一个简单的方法来处理你的问题是使用"cloud_firestore"包中。我将在下面创建一个示例代码…
注意:在使用Firestore之前,您必须首先确保您已经初始化了FlutterFire!点击此链接: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(),
);
},
);
}
}
如果您在Firebase实时数据库中有数据,您可以通过其onValue
流侦听该数据的更新。您可以通过使用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);
}
)
)
我推荐观看这个很棒的代码视频:Firebase实时数据库和Flutter - firecast