扑朔迷离地显示Firestore数据中的卡片

时间:2019-03-09 22:09:39

标签: android firebase flutter google-cloud-firestore

我最近试图制作Flutter应用程序,该应用程序从Google Cloud Firestore获取数据流,并在新屏幕上以卡的形式显示给用户。我碰到了this网站,并密切关注了该示例以从流数据中创建列表视图,并且无需花费太多精力就可以实现该视图。这就是它的样子...

具有列表视图的Flutter应用成功实现: enter image description here

但是问题是,当我尝试将输出转换为卡片而不是简单的列表视图时,我收到一条警告,提示我的小部件溢出。在下面看看...

出现卡时出现溢出警告: enter image description here

我试图将整个窗口小部件放置在一个受约束的框中,并且还尝试将收缩包装属性设置为true,但似乎无济于事。如果有人可以帮助我找出我的错处并指出正确的方向,我将感到非常高兴。 这是我编写的用于使用Firestore从streamBuilder类实现卡布局的全部代码...

(PS:卡布局和ListView布局由该应用程序右上角的图标之类的图形显示(未在图片中显示))

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';

void main() => runApp(FireList());

class FireList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Listview',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyListView(),
    );
  }
}

class MyListView extends StatefulWidget {
  @override
  _MyListViewState createState() => _MyListViewState();
}

class _MyListViewState extends State<MyListView> {
  int _upCounter = 0;
  int _downCounter = 0;
  var _newdata;
  var myDatabase = Firestore.instance;

  void _putdata() {
    var myDatabase = Firestore.instance;
    myDatabase.collection('newDoc1').document("outsideData$_upCounter").setData(
      {
        "data": "Uploaded outsider data $_upCounter",
      },
    );
    _upCounter++;
  }

  @override
  Widget build(BuildContext context) {
    _putdata();
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebse Listview'),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => MyList()),
              );
            },
            icon: Icon(Icons.multiline_chart),
          )
        ],
      ),
      // body: Center(
      //   child: Text(
      //       "Cloud Firestore contains this sentence:\nFetch Attemp: $_downCounter\nData: $_datafromfirestore"),
      // ),
      body: StreamBuilder(
        stream: myDatabase.collection('newDoc1').snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            Center(
              child: Text("\nCaught an error in the firebase thingie... :| "),
            );
          }
          if (!snapshot.hasData) {
            return Center(
              child: Text("\nHang On, We are building your app !"),
            );
          } else {
            var mydata = snapshot.data;
            print(mydata);
            _newdata = mydata.documents[_downCounter]["data"];
            return Center(
              child: Text(
                  "Cloud Firestore contains this sentence:\nFetch Attempt: $_downCounter\nData: $_newdata"),
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _downCounter++;
          });
        },
        child: Icon(Icons.cloud_download),
        tooltip: 'Download Data',
      ),
    );
  }
}

class MyList extends StatefulWidget {
  @override
  _MyListState createState() => _MyListState();
}

class _MyListState extends State<MyList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ListView Firestore"),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance.collection("newDoc1").snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) return new Text('${snapshot.error}');
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return new Center(child: new CircularProgressIndicator());
            default:
              // return ListView(
              //   padding: EdgeInsets.fromLTRB(10, 20, 10, 30),
              //   children:
              //       snapshot.data.documents.map((DocumentSnapshot document) {
              //     return new ListTile(
              //       title: new Text(document['data']),
              //     );
              //   }).toList(),
              // );
              return Card(
                child: Column(
                  children: <Widget>[
                    ListView(
                      shrinkWrap: true,
                      children: snapshot.data.documents.map(
                        (DocumentSnapshot document) {
                          return new ListTile(
                            title: new Text(document['data']),
                          );
                        },
                      ).toList(),
                    ),
                  ],
                ),
              );
          }
        },
      ),
    );
  }
}

这是我的Cloud Firestore文档的样子:

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为您想在Card右边显示所有数据吗?

我编辑您的代码,该代码应该对您有用:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(FireList());

class FireList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Listview',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyListView(),
    );
  }
}

class MyListView extends StatefulWidget {
  @override
  _MyListViewState createState() => _MyListViewState();
}

class _MyListViewState extends State<MyListView> {
  int _upCounter = 0;
  int _downCounter = 0;
  var _newdata;
  var myDatabase = Firestore.instance;

  void _putdata() {
    var myDatabase = Firestore.instance;
    myDatabase.collection('newDoc1').document("outsideData$_upCounter").setData(
      {
        "data": "Uploaded outsider data $_upCounter",
      },
    );
    _upCounter++;
  }

  @override
  Widget build(BuildContext context) {
    _putdata();
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebse Listview'),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => MyList()),
              );
            },
            icon: Icon(Icons.multiline_chart),
          )
        ],
      ),
      // body: Center(
      //   child: Text(
      //       "Cloud Firestore contains this sentence:\nFetch Attemp: $_downCounter\nData: $_datafromfirestore"),
      // ),
      body: StreamBuilder(
        stream: myDatabase.collection('newDoc1').snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            Center(
              child: Text("\nCaught an error in the firebase thingie... :| "),
            );
          }
          if (!snapshot.hasData) {
            return Center(
              child: Text("\nHang On, We are building your app !"),
            );
          } else {
            var mydata = snapshot.data;
            print(mydata);
            _newdata = mydata.documents[_downCounter]["data"];
            return Center(
              child: Text(
                  "Cloud Firestore contains this sentence:\nFetch Attempt: $_downCounter\nData: $_newdata"),
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _downCounter++;
          });
        },
        child: Icon(Icons.cloud_download),
        tooltip: 'Download Data',
      ),
    );
  }
}

class MyList extends StatefulWidget {
  @override
  _MyListState createState() => _MyListState();
}

class _MyListState extends State<MyList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ListView Firestore"),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance.collection("newDoc1").snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) return new Text('${snapshot.error}');
          switch (snapshot.connectionState) {
            case ConnectionState.none:
            case ConnectionState.waiting:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ConnectionState.active:
            case ConnectionState.done:
              if (snapshot.hasError)
                return Center(child: Text('Error: ${snapshot.error}'));
              if (!snapshot.hasData) return Text('No data finded!');
              return Card(
                child: SingleChildScrollView(
                  child: Column(
                    children:
                      snapshot.data.documents.map((DocumentSnapshot document){
                        return new Text(document['data']);
                      }).toList()
                  ),
                ),
              );
          }
        },
      ),
    );
  }
}

您也可以使用ListView来完成此解决方案,但是我认为这要简单得多。