我无法从 Firestore Flutter 检索和查看数据

Posted

技术标签:

【中文标题】我无法从 Firestore Flutter 检索和查看数据【英文标题】:I cannot retrieve and view data from Firestore Flutter 【发布时间】:2021-08-15 02:11:57 【问题描述】:

#HOME:这是链接到 FeatureProducts() 的主页

而且我无法检索数据“产品”,它总是返回 nil。

我想从 Firebase 检索数据到 Listview。

这是我的 Firebase 云火存储 Firebase 数据库的图片

我用很多方法尝试了很多次,所有代码都没有给出任何错误,但是当我运行应用程序并打开活动时,数据无法显示它们将为空,

import 'package:farmers_ecommerce/commons/common.dart';

import 'package:farmers_ecommerce/db/product.dart';

import 'package:farmers_ecommerce/pages/product_search.dart';
import 'package:farmers_ecommerce/provider/product.dart';
import 'package:farmers_ecommerce/provider/user_provider.dart';
import 'package:farmers_ecommerce/widget/featured_products.dart';
import 'package:farmers_ecommerce/widget/product_card.dart';
import 'package:farmers_ecommerce/widgets/custom_text.dart';

import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'cart.dart';
import 'order.dart';

class HomePage extends StatefulWidget 
@override
_HomePageState createState() => _HomePageState();
 

class _HomePageState extends State<HomePage> 
final _key = GlobalKey<ScaffoldState>();
ProductServices _productServices = ProductServices();


@override
Widget build(BuildContext context) 

final userProvider = Provider.of<UserProvider>(context);
final productProvider = Provider.of<ProductProvider>(context);

return Scaffold(
  key: _key,
  backgroundColor: Colors.white,
  endDrawer: Drawer(
    child: ListView(
      children: <Widget>[
        UserAccountsDrawerHeader(
          decoration: BoxDecoration(color: Colors.black),
          accountName: CustomText(
            text: userProvider.userModel?.name ?? "username lading...",
            color: Colors.white,
            weight: FontWeight.bold,
            size: 18,
          ),
          accountEmail: CustomText(
            text: userProvider.userModel?.email ?? "email loading...",
            color: Colors.white,
          ),
        ),
        ListTile(
          onTap: () async
            await userProvider.getOrders();
            changeScreen(context, OrdersScreen());
          ,
          leading: Icon(Icons.bookmark_border),
          title: CustomText(text: "My orders"),
        ),

        ListTile(
          onTap: () async
           userProvider.signOut();
          ,

        leading: Icon(Icons.exit_to_app),

        title: CustomText(text: "Log out"),
          ),
          ],
         ),
        ),

       body: SafeArea(
       child: ListView(
       children: <Widget>[
       //         Custom App bar

       Stack(
       children: <Widget>[

            Positioned(
              top: 10,
              right: 20,
              child: Align(
                  alignment: Alignment.topRight,
                  child: GestureDetector(
                      onTap: () 
                        _key.currentState.openEndDrawer();
                      ,
                      child: Icon(Icons.menu))),
            ),
            Positioned(
              top: 10,
              right: 60,
              child: Align(
                  alignment: Alignment.topRight,
                  child: GestureDetector(
                      onTap: ()
                        changeScreen(context, CartScreen());
                      ,
                      child: Icon(Icons.shopping_cart))),
            ),
            Positioned(
              top: 10,
              right: 100,
              child: Align(
                  alignment: Alignment.topRight, child: GestureDetector(
                  onTap: ()
                    _key.currentState.showSnackBar(SnackBar(
                        content: Text("User profile")));
                  ,
                  child: Icon(Icons.person))),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'What are\nyou Shopping for?',
                style: TextStyle(
                    fontSize: 30,
                    color: Colors.black.withOpacity(0.6),
                    fontWeight: FontWeight.w400),
              ),
            ),
          ],
        ),

        //          Search Text field
        //            Search(),

        Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  bottomRight: Radius.circular(20),
                  bottomLeft: Radius.circular(20))),
          child: Padding(
            padding: const EdgeInsets.only(
                top: 8, left: 8, right: 8, bottom: 10),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.2),
                borderRadius: BorderRadius.circular(20),
              ),
              child: ListTile(
                leading: Icon(
                  Icons.search,
                  color: Colors.black,
                ),
                title: TextField(
                  textInputAction: TextInputAction.search,
                  onSubmitted: (pattern)async
                    await productProvider.search(productName: pattern);
                    changeScreen(context, ProductSearchScreen());
                  ,
                  decoration: InputDecoration(
                    hintText: "fashion....",
                    border: InputBorder.none,
                  ),
                ),
              ),
            ),
          ),
        ),

        //            featured products
        Row(
        children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(14.0),
              child: Container(
                  alignment: Alignment.centerLeft,
                  child: new Text('Featured products')),
            ),
          ],
        ),
        FeaturedProducts(), 
 **this is the feature products. i cannot see any thing on here. 
         its blank**

        //          recent products
        Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(14.0),
              child: Container(
                  alignment: Alignment.centerLeft,
                  child: new Text('Recent products')),
            ),
          ],
        ),

        Column(
          children: productProvider.products
              .map((item) => GestureDetector(
            child: ProductCard(
              product: item,
            ),
          ))
              .toList(),
        )
      ],
    ),
  ),
);
  
  

#FEATURED PRODUCT:它链接到 ProductProvider,它从 数据库

     import 'package:farmers_ecommerce/provider/product.dart';
     import 'package:flutter/material.dart';
     import 'package:provider/provider.dart';

     import 'featured_card.dart';

     class FeaturedProducts extends StatefulWidget 
     @override
     _FeaturedProductsState createState() => _FeaturedProductsState();
     

    class _FeaturedProductsState extends State<FeaturedProducts> 
    @override
    Widget build(BuildContext context) 
    final productProvider = Provider.of<ProductProvider>(context);

    return Container(
    height: 230,
    child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: productProvider.products.length,
        itemBuilder: (_, index) 
          return FeaturedCard(
            product: productProvider.products[index],
          );
        ));
      
      

#产品供应商 //我觉得提供者没有加载任何产品

      import 'package:farmers_ecommerce/db/product.dart';

      import 'package:farmers_ecommerce/models/product.dart';

      import 'package:flutter/material.dart';

   class ProductProvider with ChangeNotifier
   ProductServices _productServices = ProductServices();
   List<ProductModel> products = [];
   List<ProductModel> productsSearched = [];


   ProductProvider.initialize()
   loadProducts();
   

   loadProducts()asyncenter code here
   products = await _productServices.getProducts();
   notifyListeners();
  

 Future search(String productName)async
 productsSearched = await _productServices.searchProducts(productName: productName);
 notifyListeners();
 

 

//数据库到火力存储 //我尝试使用流生成器,但使用 Future 无法正常工作。

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:farmers_ecommerce/models/product.dart';


class ProductServices 
String collection = "products";
FirebaseFirestore _firestore = FirebaseFirestore.instance;

Future<List<ProductModel>> getProducts() async =>
  _firestore.collection(collection).get().then((result) 
    List<ProductModel> products = [];
    for (DocumentSnapshot product in result.docs) 
      products.add(ProductModel.fromSnapshot(product));
    
    return products;
  );

 Future<List<ProductModel>> searchProducts(String productName) 
// code to convert the first character to uppercase
String searchKey = productName[0].toUpperCase() + productName.substring(1);
return _firestore
    .collection(collection).  //return fire base
    .orderBy("name")
    .startAt([searchKey])
    .endAt([searchKey + '\uf8ff'])
    .get()
    .then((result) 
  List<ProductModel> products = [];
  for (DocumentSnapshot product in result.docs) 
    products.add(ProductModel.fromSnapshot(product));
  
  return products;
);


【问题讨论】:

【参考方案1】:

在您的ProductServices 中更改此功能:

Future<List<ProductModel>> getProducts() async 
      QuerySnapshot result= await _firestore.collection(collection).get();
      List<ProductModel> products = [];
      for (DocumentSnapshot product in result.docs) 
        products.add(ProductModel.fromSnapshot(product));
      
      return products;

    

如果你使用thenreturn 将在代码流已经离开函数时被调用。为避免这种情况,您需要await 结果。

【讨论】:

您能否在返回之前记录products的值并检查里面是否有东西。

以上是关于我无法从 Firestore Flutter 检索和查看数据的主要内容,如果未能解决你的问题,请参考以下文章

Flutter Firestore:从 Firestore 中检索数据并在 Flutter 中显示为小部件

从 Flutter 中的 Firestore 检索数据后的空列表

如何使用 Flutter 中的 UserID 从 Firebase Firestore 检索数据?

Flutter - 如何从 Firestore 中检索 ID 列表并在 GridView 中显示它们的项目?

Flutter web:从 Firestore 地图检索的值在添加到列表时被截断

Flutter Firestore 使用异步检索所有文档内容