我是Flutter的新手,我想知道所有构建器小部件及其主要区别(Future Builder与Stream Builder?)以及将它们准确放置在何处。带有Builder小部件的示例可能很容易理解。预先感谢。
答案 0 :(得分:0)
FutureBuilder的行为与配置有future?.asStream()的StreamBuilder相同,不同之处在于后者可能会显示带有ConnectionState.active的快照,具体取决于流的实现方式。
StreamBuilder可以与Firebase,传感器事件和网络连接状态的数据一起使用
以下链接将更好地了解未来和流的工作方式:Information about future and streams in dart
FutureBuilder和ListView Builder,例如: 代码:
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: getPosts(),
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text("Loading..."),
SizedBox(
height: 50.0,
),
CircularProgressIndicator()
],
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return ListTile(
title: Text(snapshot.data[index].data["title"]),
onTap: () => navigateToDetail(snapshot.data[index]));
},
);
}
},
),
);
}
StreamBuilder和ListView Builder,例如: 代码:
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection("posts").snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return new Text('Error: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text("Loading..."),
SizedBox(
height: 50.0,
),
CircularProgressIndicator()
],
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (_, index) {
return Card(
child: ListTile(
title: Text(
snapshot.data.documents[index].data["title"]), // getting the data from firestore
),
);
},
);
}
},
),
),
);
}
注意:我使用FutureBuilder遇到的唯一问题不是我在使用FutureBuilder添加数据时就无法正确获取数据。使用StreamBuilder时,我没有遇到同样的问题,它工作正常。