![](/img/trans.png)
[英]I am not able to retrieve data from firebase database in my flutter app. I don't know what is wrong in my code
[英]I cant retrieve firebase data to my flutter app
我無法將數據從 firebase 加載到我的顫振應用程序中。 那里顯示錯誤。 我不知道為什么會這樣。 主要是我想從firebase檢索數據。 但是當我運行這段代碼時它不起作用。 可能是我的代碼中存在一些問題。 我需要解決方案
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "xyz",
home: Scaffold(
appBar: AppBar(
title: Text("Firebase"),
centerTitle: true,
),
body: FirstApp(),
),
);
}
}
class FirstApp extends StatefulWidget {
const FirstApp({Key? key}) : super(key: key);
@override
State<FirstApp> createState() => _FirstAppState();
}
class _FirstAppState extends State<FirstApp> {
var firestoreDB =
FirebaseFirestore.instance.collection("0xethocity").snapshots();
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: firestoreDB,
builder: (context, AsyncSnapshot snapshot) {
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, int index) {
return Text(snapshot.data.documents[index]['title']);
});
},
);
}
}
實際上 Stream builder 是一個異步任務,因此您必須等待並檢查才能嘗試使用數據。 嘗試 -
return StreamBuilder(
stream: firestoreDB,
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, int index) {
return Text(snapshot.data.documents[index]['title']);
}
);
},
);
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.