[英]Unable to query data from Firebase
I'm trying to retrieve data from Firebase. Here's my code snippet我正在尝试从 Firebase 检索数据。这是我的代码片段
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// DatabaseReference ref = FirebaseDatabase.instance.ref();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
final docRef = FirebaseFirestore.instance.collection('data').doc("rules");
docRef.get().then(
(DocumentSnapshot doc) {
final data = doc.data() as Map<String, dynamic>;
return MyHomePage(title: 'ARNET Helper',
rules: data['ruleslist']);
},
onError: (e) => print("Error getting document: $e"),
);
return Spinner(text: "Unable to retrieve data");
}
}
Here's the corresponding Firebase database screenshot下面是对应的Firebase数据库截图
I do have the google-services.json added to the android/app folder.我确实将 google-services.json 添加到 android/app 文件夹中。 But with the above snippet, lines from the "then" block don't seem to get hit and the spinner (ie return Spinner(text: "Unable to retrieve data");) is always returned.
但是对于上面的代码片段,“then”块中的行似乎没有被击中并且微调器(即 return Spinner(text: "Unable to retrieve data");)总是被返回。
I do have these lines added to AndroidManifest.xml我确实将这些行添加到 AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
I tried to debug it.我试着调试它。 But the breakpoint at line 46 is never hit.
但是第 46 行的断点从未被击中。 Instead the execution goes straight to line 52. What am I missing?
相反,执行直接进入第 52 行。我错过了什么?
I've even tried using FutureBuilder as suggested by one of the commenters.我什至尝试过按照一位评论者的建议使用 FutureBuilder。 I always get "Something went wrong.." spinner
我总是得到“出了点问题..”微调器
@override
Widget build(BuildContext context) {
CollectionReference data = FirebaseFirestore.instance.collection('data');
return FutureBuilder<DocumentSnapshot>(
future: data.doc('rules').get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Spinner(text: 'Something went wrong...');
}
if (snapshot.hasData && !snapshot.data!.exists) {
return Spinner(text: 'Document does not exist...');
}
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data = snapshot.data! as Map<String, dynamic>;
return MyHomePage(title: 'ARNET Helper', rules: data['ruleslist'].entries.toList() as List<dynamic>);
}
return Spinner(text: 'Loading...');
},
);
}
}
The problem is that get()
is an asynchronous operation, and you can't return widgets asynchronously in build
.问题是
get()
是一个异步操作,你不能在build
中异步返回小部件。
The simplest way to fix this is to use a FutureBuilder
:解决此问题的最简单方法是使用
FutureBuilder
:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
return FutureBuilder<String>(
future: FirebaseFirestore.instance.collection('data').doc("rules").get(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> asyncSnapshot) {
if (snapshot.hasData) {
final data = asyncSnapshot.data!.data() as Map<String, dynamic>;
return MyHomePage(title: 'ARNET Helper', rules: data['ruleslist']);
}
else if (snapshot.hasError) {
return Text("Error: ${snapshot.error}")
}
else {
return Text("Loading user data...")
}
}
)
}
Did you initialize the Firebase Instance?您是否初始化了 Firebase 实例?
await Firebase.initializeApp()
Not sure what the issue was but the config below worked.不确定是什么问题,但下面的配置有效。
pubspec.yaml pubspec.yaml
firebase_core: ^1.24.0
cloud_firestore: ^3.5.0
FutureBuilder query FutureBuilder 查询
@override
Widget build(BuildContext context) {
CollectionReference data = FirebaseFirestore.instance.collection('data');
return FutureBuilder<DocumentSnapshot>(
future: data.doc("rules").get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Spinner(text: 'Something went wrong...');
}
if (snapshot.hasData && !snapshot.data!.exists) {
return Spinner(text: 'Document does not exist...');
}
if (snapshot.connectionState == ConnectionState.done) {
final data = snapshot.data!.get('ruleslist') ;
return MyHomePage(title: 'ARNET Helper', rules: data);
}
return Spinner(text: 'Loading...');
},
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.