Flutter - Connecting to Firestore

Flutter - Connecting to Firestore

[[../../../_notes/_tech/Flutter/Flutter]]

Make sure you’ve configured your project using the instructions in [[Flutter - Firebase Setup]]

Add the dependency to your pubspec.yaml

flutter pub add cloud_firestore

Make sure to run packages get to pull the new dependencies

iOS additional Config

I had an issue when trying to debug my app. Error read [!] Automatically assigning platform iOS with version 9.0 on target Runner because no platform was specified. Solution found on this site states you should: Open the Podfile and uncomment the second line. Set the platform :ios to 11

Usage

Add the imports

import 'package:cloud_firestore/cloud_firestore.dart';

Create an instance of firestore

FirebaseFirestore firestore = FirebaseFirestore.instance;

Interact with a Collection

CollectionReference users = FirebaseFirestore.instance.collection('users');

Checkout the official docs for more details

Test your configuration

Update the _incrementCounter() function with the code below.

  CollectionReference counterCollection =
      FirebaseFirestore.instance.collection('counter');
      
  void _incrementCounter() {
    setState(() {
      _counter++;
      counterCollection.doc("theCounter").set({"count": _counter});
    });
  }

This will update a value in the database for button click.

  • [[Flutter - Firebase Setup]]

References