Flutter Firestore:从 Firestore 中检索数据并在 Flutter 中显示为小部件
Posted
技术标签:
【中文标题】Flutter Firestore:从 Firestore 中检索数据并在 Flutter 中显示为小部件【英文标题】:Flutter Firestore : Retrieve data from Firestore and display as widget in flutter 【发布时间】:2021-11-28 21:45:45 【问题描述】:我在 Firestore 上有一个名为“orders”的集合,其中包含一个文档列表 我想在我的 Flutter 应用程序中显示为小部件。文档的数据类型为字符串、数字和地图。我正在使用 FutureBuilder 和 ListViewBuilder 来返回一个小部件,
所以我需要将数据从地图转换为我假设的列表?但是我被卡住了......
订单屏幕
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:my_app/widgets/order_item.dart';
import '../providers/orders.dart' show Orders;
import 'package:provider/provider.dart';
class OrdersScreen extends StatefulWidget
const OrdersScreen(Key? key) : super(key: key);
static const routeName = '/orders-screen';
@override
State<OrdersScreen> createState() => _OrdersScreenState();
class _OrdersScreenState extends State<OrdersScreen>
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Theme.of(context).primaryColor,
title: const Text(
'Order History',
),
),
body: FutureBuilder<QuerySnapshot>(
future: FirebaseFirestore.instance.collection('orders').get(),
builder: (context, snapshot)
if (snapshot.connectionState == ConnectionState.waiting)
return const Center(
child: CircularProgressIndicator(),
);
else
if (snapshot.error != null)
return const Center(
child: Text('An error has occured'),
);
else
final List<DocumentSnapshot> documents = snapshot.data!.docs;
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) => ????,
),
);
,
),
);
【问题讨论】:
请同时添加firebase数据库结构 我刚刚做了..... 【参考方案1】:我建议您使用 Stream builder 从 firestore 返回一个小部件, 并像这样使用它;
Stream<QuerySnapshot> _orderStream= FirebaseFirestore.instance.collection('orders').snapshots();
StreamBuilder<QuerySnapshot>(
stream: _orderStream,
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot)
if (snapshot.hasError)
return const Text(' ');
if (snapshot.connectionState == ConnectionState.waiting)
return const Text(" ");
return Colmn(
children: snapshot.data.docs
.map((DocumentSnapshot document)
Map<String, dynamic> data =
document.data() as Map<String, dynamic>;
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) =>
/// whatever widget you want to build, relace it with container
Container(child: Text(data['your feild']),),
);
,
),
【讨论】:
嗨@navidanchitrali,我不知道为什么我需要sizedBox 和GridView?此外,即使我这样做,我也会在这里收到一个错误:children: snapshot.data.docs,上面写着参数类型“Iterable”不能分配给参数类型“List以上是关于Flutter Firestore:从 Firestore 中检索数据并在 Flutter 中显示为小部件的主要内容,如果未能解决你的问题,请参考以下文章
Flutter Firestore:从 Firestore 中检索数据并在 Flutter 中显示为小部件
无法从 Firestore 文档中删除字段 (Flutter)
从 Flutter 移动应用程序调用 Firestore 是不是安全?