gpt4 book ai didi

flutter - 在 PageView 中显示流中的单个项目

转载 作者:IT王子 更新时间:2023-10-29 07:23:11 28 4
gpt4 key购买 nike

我有以下小部件,它使用 PageView 在单独的页面中显示每本书。

class Books extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _BooksState();
}
}

class _BooksState extends State<Books> {
PageController controller = PageController();
String title = 'Title of the AppBar';

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: PageView.builder(
controller: controller,
scrollDirection: Axis.horizontal,
itemBuilder: (context, position) {
return Center(position.toString());
// return BooksStream();
},
onPageChanged: (x) {
setState(() {
title = '$x';
});
},
),
);
}
}

我还有 FlutterFire 文档中的这个示例小部件,用于从 firestore 集合中获取所有文档:

class BooksStream extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('Books').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return new ListView(
children:
snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['title']),
subtitle: new Text(document['author']),
);
}).toList(),
);
}
},
);
}
}

在 PageView.builder 中,当我返回 BooksStream() 时,它会在每一页上显示所有书籍,这是完全正常的。

但是我如何使用 StreamBuilder 在 PageView 的单独页面上显示每本书?

谢谢。

最佳答案

您可以像这样在 StreamBuilder builder 字段中返回 PageView.builder:

class BooksStream extends StatelessWidget {
PageController controller = PageController();

@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('Books').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return PageView.builder( // Changes begin here
controller: controller,
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, position) {
final document = snapshot.data.documents[position];

return ListTile(
title: new Text(document['title']),
subtitle: new Text(document['author']));
}
);
}
},
);
}
}

然后就在 Scaffoldbody 中,您可以实例化 BooksStream

关于flutter - 在 PageView 中显示流中的单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485485/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com