Firebase 从firestore到Flatter的流生成器
我想知道如何使用streambuilder从firestore获取数据到Flatter应用程序。我创建了必要的样板代码,我已经在下面的代码中构建并运行了小部件Firebase 从firestore到Flatter的流生成器,firebase,google-cloud-firestore,flutter,Firebase,Google Cloud Firestore,Flutter,我想知道如何使用streambuilder从firestore获取数据到Flatter应用程序。我创建了必要的样板代码,我已经在下面的代码中构建并运行了小部件 headimageassetpath只是firestore中存在的URL字符串 @override Widget build(BuildContext context) { return Scaffold( body: new StreamBuilder( stream: Firest
headimageassetpath
只是firestore中存在的URL字符串
@override
Widget build(BuildContext context) {
return Scaffold(
body:
new StreamBuilder(
stream: Firestore.instance.collection('Items').snapshots(),
builder: (_, AsyncSnapshot<QuerySnapshot> snapshot) {
var items = snapshot.data?.documents ?? [];
return new Lost_Card(
headImageAssetPath : snapshot.data.documents.map()(['url'],)
);
},
)
@覆盖
小部件构建(构建上下文){
返回脚手架(
正文:
新StreamBuilder(
流:Firestore.instance.collection('Items').snapshots(),
生成器:(\ux,异步快照){
var项目=快照.数据?文档???[];
归还新的遗失卡(
headImageAssetPath:snapshot.data.documents.map()
);
},
)
我的火炉店:
完整代码:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class LostPage extends StatefulWidget {
@override
_LostPage createState() => new _LostPage();
}
class _LostPage extends State<LostPage> {
//temp vars
final String firebasetest = "Test";
//firestore vars
final DocumentReference documentReference =
Firestore.instance.document("Items/Rusty");
//CRUD operations
void _add() {
Map<String, String> data = <String, String>{
"name": firebasetest,
"desc": "Flutter Developer"
};
documentReference.setData(data).whenComplete(() {
print("Document Added");
}).catchError((e) => print(e));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body:
new StreamBuilder(
stream: Firestore.instance.collection('Items').snapshots(),
builder: (_, AsyncSnapshot<QuerySnapshot> snapshot) {
var items = snapshot.data?.documents ?? [];
return new Lost_Card(
headImageAssetPath : snapshot.data.documents.map()(['url'],)
);
},
)
/*new Lost_Card(
headImageAssetPath: "https://i.imgur.com/FtaGNck.jpg" ,
title: "Mega Dish",
noro: "old",
)*/,
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
onPressed: _add),
);
}
}
class Lost_Card extends StatelessWidget
{
//All the card variables
final String headImageAssetPath;
final IconData icon;
final Color iconBackgroundColor;
final String title;
final String noro;
final int price;
final ShapeBorder shape;
Lost_Card({
this.headImageAssetPath, //used
this.icon,
this.iconBackgroundColor,
this.title, //used
this.noro, //used
this.price,
});
@override
Widget build(BuildContext context) {
// TODO: implement build
return GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
children: <Widget>[
Card(
child: Column(
// mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height / 4,
width: MediaQuery.of(context).size.height / 2.5,
child: DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
headImageAssetPath),
fit: BoxFit.cover),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Align(
alignment: FractionalOffset.topLeft,
child: CircleAvatar(
backgroundColor: Colors.redAccent,
radius: 15.0,
child: Text(
noro,
textScaleFactor: 0.5,
),
),
),
),
Align(
alignment: FractionalOffset.topRight,
child: Container(
color: Colors.blueAccent,
height: 35.0,
width: 35.0,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.account_circle),
Text(
"1P",
textScaleFactor: 0.5,
),
],
),
),
),
),
],
),
),
Center(
child: Container(
padding: const EdgeInsets.all(8.0),
alignment: FractionalOffset.bottomCenter,
child: Text(
title,
style: TextStyle(
fontWeight: FontWeight.w700,
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
FlatButton(
child: Text(
"Add To Cart",
style: TextStyle(color: Colors.grey[500]),
),
onPressed: () => null,
),
Text(
"\$5",
style: TextStyle(color: Colors.grey[500]),
)
],
)
],
),
),
],
);
}
}
导入“包装:颤振/材料.省道”;
导入“包:cloud_firestore/cloud_firestore.dart”;
类LostPage扩展StatefulWidget{
@凌驾
_LostPage createState()=>new_LostPage();
}
类_LostPage扩展状态{
//温度变量
最终字符串firebasetest=“Test”;
//消防车
最终文件参考文件参考=
Firestore.instance.document(“Items/Rusty”);
//积垢作业
void_add(){
地图数据={
“名称”:firebasetest,
“描述”:“颤振开发者”
};
documentReference.setData(数据)。完成时(){
打印(“添加文件”);
}).catchError((e)=>打印(e));
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
正文:
新StreamBuilder(
流:Firestore.instance.collection('Items').snapshots(),
生成器:(\ux,异步快照){
var项目=快照.数据?文档???[];
归还新的遗失卡(
headImageAssetPath:snapshot.data.documents.map()
);
},
)
/*新失联卡(
headImageAssetPath:“https://i.imgur.com/FtaGNck.jpg" ,
标题:“超级美食”,
诺罗:“老”,
)*/,
floatingActionButton:新的floatingActionButton(
子:新图标(Icons.add),
按下按钮:_添加),
);
}
}
类丢失\u卡扩展无状态小部件
{
//所有卡片变量
最终字符串头映像AssetPath;
最终的Iconda图标;
最终颜色iconBackgroundColor;
最后的字符串标题;
最后一串诺罗;
最终国际价格;
最终形状订单形状;
遗失卡({
this.headImageAssetPath,//已使用
这个图标,
这是我的背景色,
this.title,//已使用
this.noro,//已使用
这个价格,,
});
@凌驾
小部件构建(构建上下文){
//TODO:实现构建
返回GridView.count(
收缩膜:对,
交叉轴计数:2,
儿童:[
卡片(
子:列(
//mainAxisSize:mainAxisSize.max,
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
扩大(
子:堆栈(
fit:StackFit.expand,
儿童:[
容器(
高度:MediaQuery.of(context).size.height/4,
宽度:MediaQuery.of(context).size.height/2.5,
孩子:装饰盒(
装饰:盒子装饰(
图像:装饰图像(
图片:NetworkImage(
headImageAssetPath),
安装:BoxFit.盖),
),
),
),
填充物(
填充:常数边集全部(8.0),
子对象:对齐(
对齐:分馏loffset.topLeft,
孩子:圆环星(
背景颜色:Colors.redAccent,
半径:15.0,
子:文本(
诺罗,
textScaleFactor:0.5,
),
),
),
),
对齐(
对齐:分馏Loffset.topRight,
子:容器(
颜色:Colors.blueAccent,
身高:35.0,
宽度:35.0,
儿童:中心(
子:列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
图标(图标、帐户和圆圈),
正文(
“1P”,
textScaleFactor:0.5,
),
],
),
),
),
),
],
),
),
居中(
子:容器(
填充:常数边集全部(8.0),
对齐:分馏Loffset.bottomCenter,
子:文本(
标题
样式:TextStyle(
fontWeight:fontWeight.w700,
),
),
),
),
划船(
mainAxisAlignment:mainAxisAlignment.spaceAround,
儿童:[
扁平按钮(
子:文本(
“添加到购物车”,
样式:TextStyle(颜色:Colors.grey[500]),
),
onPressed:()=>null,
),
正文(
"\$5",
样式:TextStyle(颜色:Colors.grey[500]),
)
],
)
],
),
),
],
);
}
}
实际应用程序
请嘘
body: new StreamBuilder(
stream: Firestore.instance.collection("collection").snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Text(
'No Data...',
);
} else {
<DocumentSnapshot> items = snapshot.data.documents;
return new Lost_Card(
headImageAssetPath : items[0]["url"]
);
}
return new ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.documents[index];
return new Lost_Card(
headImageAssetPath : ds["url"];
);
Card buildItem(DocumentSnapshot doc) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'name: ${doc.data['name']}',
style: TextStyle(fontSize: 24),
),
Text(
'todo: ${doc.data['todo']}',
style: TextStyle(fontSize: 20),
),
Text(
'Age: ${doc.data['age']}',
style: TextStyle(fontSize: 10),
),
SizedBox(
height: 12,
),
],
)
],
),
),
); }
body: ListView(
padding: EdgeInsets.all(8),
children: <Widget>[
Form(
key: _formKey,
child: buildTextFormField(),
),
StreamBuilder<QuerySnapshot>(
stream: db
.collection('CRUD')
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: snapshot.data.documents
.map((doc) => buildItem(doc))
.toList());
} else {
return SizedBox();
}
},
)
],
),
StreamBuilder<List<UData>>(
stream: AdminData().getDrivers,
builder: (context, snapshot) {
return ListView(
children: snapshot.data.map((document) {
return hadCard(
widget: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
hadText(title: document.name),
hadText(title: document.phone),
hadText(title: document.Driver),
],
),
);
}).toList(),
);
}),
final _mFirestore = FirebaseFirestore.instance;
return StreamBuilder<QuerySnapshot>(
stream:
_mFirestore.collection(kFirebaseCollectionName).snapshots(),
builder: (context, snapshots) {
if (!snapshots.hasData) {
return Center(
child: Text('Data not available',),
);
}
final messages = snapshots.data.docs;
List<Text> textWidgets = [];
messages.forEach((element) {
final messageText = element['text'];
final messageSender = element['sender'];
final textWidget = Text('$messageText, $messageSender');
textWidgets.add(messageBubbleWidget);
});
},
);