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

时间:2019-02-01 18:46:41

标签: flutter google-cloud-firestore

我有以下使用 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的单独页面上显示每本书?

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以返回 ncdump -v flash_lon file.nc | sed -e '1,/data:/d' -e '$d' | tail -n +3 > output.txt PageView.builder StreamBuilder场这样的:

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'])); } ); } }, ); } } 的{​​{1}}内部,可以实例化body