基于Firestore字段值的Flutter组件条件切换需求
Flutter 根据Firestore字段动态返回对应组件
实现思路
通过StreamBuilder监听Firestore中pr_details集合的实时数据,读取dropdowncompany字段的值,通过条件判断返回对应组件:
- 字段值为
"ซินเนติก"时,返回OverviewPurchase组件 - 字段值为
"ซินโนวิค"时,返回OverviewPurchase1组件
完整代码实现
import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class DynamicComponentPage extends StatelessWidget { const DynamicComponentPage({super.key}); @override Widget build(BuildContext context) { // 监听pr_details集合的实时数据(可根据需求调整为指定文档) final prDetailsStream = FirebaseFirestore.instance .collection('pr_details') // 如需指定单个文档,取消注释并替换ID:.doc('目标文档ID') .snapshots(); return Scaffold( appBar: AppBar(title: const Text('动态组件展示')), body: StreamBuilder<QuerySnapshot>( stream: prDetailsStream, builder: (context, snapshot) { // 加载状态处理 if (snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator()); } // 错误状态处理 if (snapshot.hasError) { return Center(child: Text('加载失败: ${snapshot.error}')); } // 无数据处理 if (!snapshot.hasData || snapshot.data!.docs.isEmpty) { return const Center(child: Text('暂无数据')); } // 获取目标字段值(此处取第一个文档,可按需调整逻辑) final targetDoc = snapshot.data!.docs.first; final companyValue = targetDoc['dropdowncompany'] as String; // 根据字段值返回对应组件 switch (companyValue) { case "ซินเนติก": return const OverviewPurchase(); case "ซินโนวิค": return const OverviewPurchase1(); default: return Center(child: Text('未知公司类型: $companyValue')); } }, ), ); } } // OverviewPurchase组件(对应ซินเนติก) class OverviewPurchase extends StatelessWidget { const OverviewPurchase({super.key}); @override Widget build(BuildContext context) { return const Center( child: Card( elevation: 4, child: Padding( padding: EdgeInsets.all(16.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( 'Overview Purchase (ซินเนติก)', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox(height: 16), // 此处替换为匹配示例图的具体组件内容 Text('ซินเนติก公司专属采购概览内容'), ], ), ), ), ); } } // OverviewPurchase1组件(对应ซินโนวิค) class OverviewPurchase1 extends StatelessWidget { const OverviewPurchase1({super.key}); @override Widget build(BuildContext context) { return const Center( child: Card( elevation: 4, child: Padding( padding: EdgeInsets.all(16.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( 'Overview Purchase 1 (ซินโนวิค)', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox(height: 16), // 此处替换为匹配示例图的具体组件内容 Text('ซินโนวิค公司专属采购概览内容'), ], ), ), ), ); } }
注意事项
- 确保项目已配置Firestore依赖,在
pubspec.yaml中添加cloud_firestore: ^最新版本号并执行flutter pub get - 若需监听单个文档的实时更新,将集合监听替换为
FirebaseFirestore.instance.collection('pr_details').doc('目标文档ID').snapshots(),并将StreamBuilder的泛型改为DocumentSnapshot - 根据实际业务调整文档读取逻辑,比如遍历多个文档或添加筛选条件
内容的提问来源于stack exchange,提问作者Phpa
相关产品推荐
相关产品推荐

