简体   繁体   中英

Flutter: Why doesn't this streambuilder work?

So, I have just began working on a flutter project and am quite new to the whole experience. I just managed to integrate firebase firestore into my project by creating a few buttons that update, remove, and add documents. However, I also wanted to add a Streambuilder with the list that is being updated on the same page. I tried each task seperately, and they all work fine and dandy, however when I combine the two, the streambuilder shows no data and the buttons won't click. How do I incorporate both buttons and a Streambuilder in one body, or one page? What can I do to combine both of these elements onto one page in the widget build method? Again, the two elements seem to be working okay by themselves if I use the Streambuilder in the body and not a children widget tag.

A picture of what the not working page looks like. Notice how the buttons are not being selected when hovered over and the streambuilder is loading infinitely: https://i.stack.imgur.com/XnfVJ.png Firebase data screenshot (security settings allow users to access the data): https://i.stack.imgur.com/oSsOL.png

Here is my code for main.dart:


  final databaseReference = Firestore.instance;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FireStore Demo'),
      ),
      body: Center(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,

        children: <Widget>[

          RaisedButton(
            child: Text('Create Record'),
            onPressed: () {
              createRecord();
            },
          ),
          RaisedButton(
            child: Text('View Record'),
            onPressed: () {
              getData();
            },
          ),
          RaisedButton(
            child: Text('Update Record'),
            onPressed: () {
              updateData();
            },
          ),
          RaisedButton(
            child: Text('Delete Record'),
            onPressed: () {
              deleteData();
            },
          ),
          StreamBuilder<QuerySnapshot>(
        stream: databaseReference.collection('books').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) return new Text('Loading...');
          return new ListView(
            children: snapshot.data.documents.map((DocumentSnapshot document) {
              return new ListTile(
                title: new Text(document['title']),
                subtitle: new Text('${document['description']} description'),
              );
            }).toList(),
          );
        },
      )
        ],
      )),
       //center
    );
  }

  void createRecord() async {
    await databaseReference.collection("books")
        .document("1")
        .setData({
          'title': 'Mastering Flutter',
          'description': 'Programming Guide for Dart'
        });

    DocumentReference ref = await databaseReference.collection("books")
        .add({
          'title': 'Flutter in Action',
          'description': 'Complete Programming Guide to learn Flutter'
        });
    print(ref.documentID);
  }

  void getData() {
    databaseReference
        .collection("books")
        .getDocuments()
        .then((QuerySnapshot snapshot) {
      snapshot.documents.forEach((f) => print('${f.data}}'));
    });
  }

  void updateData() {
    try {
      databaseReference
          .collection('books')
          .document('1')
          .updateData({'description': 'Head First Flutter'});
    } catch (e) {
      print(e.toString());
    }
  }

  void deleteData() {
    try {
      databaseReference
          .collection('books')
          .document('1')
          .delete();
    } catch (e) {
      print(e.toString());
    }
  }
}



Still don't know why the code above didn't work, but putting the streambuilder within an Expanded block seemed to do the trick. Both widgets are working fine as of now.

import 'package:flutter/material.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(new MediaQuery( data: new MediaQueryData(), child: new MaterialApp(home: new MyApp())));

      child: Column(
    crossAxisAlignment: CrossAxisAlignment.stretch,

    children: <Widget>[

      RaisedButton(
        child: Text('Create Record'),
        onPressed: () {
          createRecord();
        },
      ),
      RaisedButton(
        child: Text('View Record'),
        onPressed: () {
          getData();
        },
      ),
      RaisedButton(
        child: Text('Update Record'),
        onPressed: () {
          updateData();
        },
      ),
      RaisedButton(
        child: Text('Delete Record'),
        onPressed: () {
          deleteData();
        },
      ),
  new Expanded(child:
    new StreamBuilder<QuerySnapshot>(
    stream: databaseReference.collection('books').snapshots(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (!snapshot.hasData) return new Text('Loading...');
      return new ListView(
        children: snapshot.data.documents.map((DocumentSnapshot document) {
          return new ListTile(
            title: new Text(document['title']),
            subtitle: new Text('${document['description']} description'),
          );
        }).toList(),
      );
    },
    )
  )
    ],
  )),
   //center
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM