Skip to content

Latest commit

 

History

History
72 lines (60 loc) · 2.95 KB

14.md

File metadata and controls

72 lines (60 loc) · 2.95 KB

Our app is now connected to Cloud Firestore!

It's time to fetch our collection (words) and use it instead of our random generated wordpairs.

  1. From Dart, you get the reference to Cloud Firestore by calling Firestore.instance. Specifically for our collection of baby names, call Firestore.instance.collection('words').snapshots() to return a stream of snapshots. Let's plug that stream of data into our Flutter UI using a StreamBuilder widget.

  2. In your IDE or editor, open lib/main.dart, then find the _buildSuggestions method. Replace the entire method with the following code:

  Widget _buildSuggestions(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('words').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return LinearProgressIndicator();

        return ListView(
          padding: EdgeInsets.all(16),
          children: snapshot.data.documents.map((data) => _buildRow(context, data)).toList(),
        );
      },
    );
  }

The StreamBuilder widget listens for updates to the database and refreshes the list whenever the data changes. When there's no data, it shows a progress indicator.

  1. The code that you just copy-pasted has a type error. It's trying to pass a list of DocumentSnapshot and BuildContext to a method that expects something else. Find the method _buildRow, then replace it with this:
  Widget _buildRow(BuildContext context, DocumentSnapshot data) {
    final pair = Entity.fromSnapshot(data);
    return ListTile(
        title: Text(
          pair.wordpair,
        ),
        trailing: Icon(
          pair.isFavorite ? Icons.favorite : Icons.favorite_border,
          color: pair.isFavorite ? Colors.red : null,
        ),
        onTap: () {});
  }
  1. We're almost there. It's necessary to change call of _buildSuggestions
class RandomWordsState extends State<RandomWords> {
  final List<WordPair> _suggestions = [];
  final Set<WordPair> _saved = {};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter dfdfd'),
          actions: <Widget>[
            // Add 3 lines from here...
            IconButton(icon: Icon(Icons.list), onPressed: _pushSaved),
          ],
        ),
        body: _buildSuggestions(context)); #add context here
  }
  1. Save the file, then hot-reload your app.
    • If you're using an IDE, just saving the file automatically performs hot-reload.
    • If you're using an editor, enter r in the command line at the same location that you ran flutter run.

You've just read from the database that you created!

If you want, you can go to the Firebase console and change the database. Your app will reflect the changes almost immediately (after all Cloud Firestore is a real-time database!).