簡體   English   中英

我無法將 Firebase 數據檢索到我的顫振應用程序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM