<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Anderson Dalbert</title>
    <description>The latest articles on DEV Community by Anderson Dalbert (@andersondalbert).</description>
    <link>https://dev.to/andersondalbert</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F327701%2F67d4b7b2-11c7-47b9-8966-f10727cf2c8d.jpg</url>
      <title>DEV Community: Anderson Dalbert</title>
      <link>https://dev.to/andersondalbert</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/andersondalbert"/>
    <language>en</language>
    <item>
      <title>How to Use Firestore To Persist Data in Flutter Apps</title>
      <dc:creator>Anderson Dalbert</dc:creator>
      <pubDate>Mon, 09 Mar 2020 15:49:02 +0000</pubDate>
      <link>https://dev.to/andersondalbert/how-to-use-firestore-to-persist-data-in-flutter-apps-11jn</link>
      <guid>https://dev.to/andersondalbert/how-to-use-firestore-to-persist-data-in-flutter-apps-11jn</guid>
      <description>&lt;p&gt;Hello there! The purpose of this arcticle is to be very objective and summarize all about how to access and make the most common queries to &lt;strong&gt;Firestore&lt;/strong&gt; using &lt;strong&gt;Flutter&lt;/strong&gt;, Google's Mobile App SDK.&lt;/p&gt;

&lt;h1&gt;
  
  
  Table of Contents
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Basics&lt;/li&gt;
&lt;li&gt;
Getting data

&lt;ul&gt;
&lt;li&gt;Get a single document&lt;/li&gt;
&lt;li&gt;Get a whole collection&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Updating data&lt;/li&gt;
&lt;li&gt;Inserting data&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Example database
&lt;/h2&gt;

&lt;p&gt;To examplify our tutorial, I'm gonna introduce a sample database which contains a simple collection of cars:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--L5OX0irW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/8WlOjwV.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--L5OX0irW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/8WlOjwV.png" alt="Example database containing data from cars"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Basics &lt;a&gt;&lt;/a&gt;
&lt;/h1&gt;

&lt;p&gt;You should use &lt;em&gt;Firestore&lt;/em&gt; object and call it's instance to access the database from Firestore:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;final Firestore database = Firestore.instance;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Now, the &lt;strong&gt;database&lt;/strong&gt; object will get you access to all collections inside your Firestore database. &lt;/p&gt;

&lt;h1&gt;
  
  
  Getting data &lt;a&gt;&lt;/a&gt;
&lt;/h1&gt;

&lt;h2&gt;
  
  
  Get a single document &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future&amp;lt;DocumentSnapshot&amp;gt; car = 
    database.collection('cars')
    .document('D3idV9o7uWT4pWvby643')
    .get();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The code above use our &lt;strong&gt;database&lt;/strong&gt; variable to access our collection of &lt;em&gt;cars&lt;/em&gt;, by passing its identifier (the collection's name) as argument. Then, we access the document we want to get, passing its unique ID. &lt;/p&gt;

&lt;p&gt;This will return a &lt;strong&gt;Future&amp;lt;DocumentSnapshot&amp;gt;&lt;/strong&gt;. A &lt;strong&gt;DocumentSnapshot&lt;/strong&gt; encapsulates all data inside an element from a collection. I suggest that you read its &lt;strong&gt;&lt;a href="https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentSnapshot"&gt;documentation&lt;/a&gt;&lt;/strong&gt;. It will get you more comfortable on how to manipulate the data inside a &lt;em&gt;DocumentSnapshot&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;So, since you have a &lt;strong&gt;Future&lt;/strong&gt; object, it means that the &lt;strong&gt;DocumentSnapshot&lt;/strong&gt; inside it only will be returned some moment after the instruction is executed, but you don't know exactly when. To extract the &lt;em&gt;DocumentSnapshot&lt;/em&gt; inside it, you can use &lt;strong&gt;then&lt;/strong&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;car.then( (DocumentSnapshot carSnapshot) =&amp;gt; { 
   /* insert here the code of what you want to do with the snapshot*/  
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Let's say, for example, that you want to access and print the property &lt;em&gt;model&lt;/em&gt; from the car:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;car.then( (carSnapshot) =&amp;gt; { 
   print(carSnapshot["model"]) 
});

/* output is: 
Honda Civic 2.0 LXR
*/
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Get a whole collection &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;To get all snapshots from a collection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stream&amp;lt;QuerySnapshot&amp;gt; stream = database.collection("cars").snapshots();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This will return a &lt;strong&gt;Stream&lt;/strong&gt; object. To iterate over the object you got to perform some operations with the data it contains, you may use a &lt;strong&gt;StreamBuilder&lt;/strong&gt;. &lt;br&gt;
Let's say, for example, that you want to show the model and year from each car you have inside your cars collection, displaying it in your app's screen.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
final Stream&amp;lt;QuerySnapshot&amp;gt; stream = database.collection("cars").snapshots();

@override
  Widget build(BuildContext context) {
    return StreamBuilder&amp;lt;QuerySnapshot&amp;gt;(
      stream: stream,
      builder: (context, snapshot) {
        if (snapshot.hasError) return ErrorDialog("Error while trying to access car data");
        switch (snapshot.connectionState) {
          case ConnectionState.active:
            return Container(
              child: ListView(
                children: List.generate(snapshot.data.documents.length, (index) {
                    DocumentSnapshot currentDocument = snapshot.data.documents[index];
                    return Text(currentDocument["model"] + " " + currentDocument["year"])
              })));

          default: return Text("Loading data");
        }
      }
    );
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h1&gt;
  
  
  How to update data &lt;a&gt;&lt;/a&gt;
&lt;/h1&gt;

&lt;p&gt;This is how you &lt;strong&gt;update data from an document&lt;/strong&gt; inside our collection of cars:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future&amp;lt;void&amp;gt; updateData = database
   .collection('cars')
   .document('D3idV9o7uWT4pWvby643')
   .updateData(
      {
      "year": 2020,
      "model": "Toyota Corolla XEI 2.0",
      "hasInsurance": true
      });
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;If you want to &lt;strong&gt;update just one field&lt;/strong&gt;, the query is just the same. You just have to pass only the field you want to update. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future&amp;lt;void&amp;gt; updateOneField = database
   .collection('cars')
   .document('D3idV9o7uWT4pWvby643')
   .updateData(
      {
      "hasInsurance": false
      });
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h1&gt;
  
  
  How to insert data &lt;a&gt;&lt;/a&gt;
&lt;/h1&gt;

&lt;p&gt;Use &lt;em&gt;setData&lt;/em&gt; method, which creates a new document by passing the ID you want the document to have.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future&amp;lt;void&amp;gt; insertData = database
   .collection("cars")
   .document("nVnAIom5wFBPL4h88w7D")
   .setData(
     {
     "model": "Tesla Model X",
     "year": 2019,
     "hasInsurance": true
     });
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This will create a new element inside our cars collection. Just remember that, if there is already a document with same ID, it will get overrided. So, it may be a good idea to check if there is already a document with the ID you want to create before using &lt;em&gt;setData&lt;/em&gt;. &lt;br&gt;
For doing so, you just have to perform a get (which you already know how to do by now) passing the ID you want to check. Then, verify if it returned a snapshot by using &lt;strong&gt;exists&lt;/strong&gt; method. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final docSnapshot = await database.collection('cars').document('nVnAIom5wFBPL4h88w7D').get();
if ( !docSnapshot.exists) {
   // insert logic to add a new document goes here
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That's it, folks! With what you learned, I'm sure you will be able to get a lot o stuff done with &lt;strong&gt;Flutter&lt;/strong&gt; and &lt;strong&gt;Firestore&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hope that helps!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>flutter</category>
      <category>firestore</category>
      <category>tutorial</category>
      <category>android</category>
    </item>
  </channel>
</rss>
