CINXE.COM

cloud_firestore example | Flutter package

<!DOCTYPE html> <html lang="en-us"><head><script src="https://www.googletagmanager.com/gtm.js?id=GTM-MX6DBN9" async="async"></script><script src="/static/hash-8pjab7lp/js/gtm.js" async="async"></script><meta charset="utf-8"/><meta http-equiv="x-ua-compatible" content="ie=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><meta name="twitter:card" content="summary"/><meta name="twitter:site" content="@dart_lang"/><meta name="twitter:description" content="Flutter plugin for Cloud Firestore, a cloud-hosted, noSQL database with live synchronization and offline support on Android and iOS."/><meta name="twitter:image" content="https://pub.dev/static/hash-8pjab7lp/img/pub-dev-icon-cover-image.png"/><meta property="og:type" content="website"/><meta property="og:site_name" content="Dart packages"/><meta property="og:title" content="cloud_firestore example | Flutter package"/><meta property="og:description" content="Flutter plugin for Cloud Firestore, a cloud-hosted, noSQL database with live synchronization and offline support on Android and iOS."/><meta property="og:image" content="https://pub.dev/static/hash-8pjab7lp/img/pub-dev-icon-cover-image.png"/><meta property="og:url" content="https://pub.dev/packages/cloud_firestore/example"/><title>cloud_firestore example | Flutter package</title><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Google+Sans:wght@400;500;700&amp;family=Google+Sans+Display:wght@400&amp;family=Google+Sans+Text:wght@400;500;700&amp;family=Google+Sans+Mono:wght@400;700&amp;display=swap"/><link rel="shortcut icon" href="/static/hash-8pjab7lp/img/flutter-logo-32x32.png"/><link rel="stylesheet" href="https://www.gstatic.com/glue/v25_0/ccb.min.css"/><link rel="search" type="application/opensearchdescription+xml" title="Dart packages" href="/osd.xml"/><link rel="canonical" href="https://pub.dev/packages/cloud_firestore/example"/><meta name="description" content="Flutter plugin for Cloud Firestore, a cloud-hosted, noSQL database with live synchronization and offline support on Android and iOS."/><link rel="alternate" type="application/atom+xml" title="Updated Packages Feed for Pub" href="/feed.atom"/><link rel="stylesheet" type="text/css" href="/static/hash-8pjab7lp/material/bundle/styles.css"/><link rel="stylesheet" type="text/css" href="/static/hash-8pjab7lp/css/style.css"/><script src="/static/hash-8pjab7lp/material/bundle/script.min.js" defer="defer"></script><script src="/static/hash-8pjab7lp/js/script.dart.js" defer="defer"></script><script src="https://www.gstatic.com/brandstudio/kato/cookie_choice_component/cookie_consent_bar.v3.js" defer="defer" data-autoload-cookie-consent-bar="true"></script><meta name="pub-page-data" content="eyJwa2dEYXRhIjp7InBhY2thZ2UiOiJjbG91ZF9maXJlc3RvcmUiLCJ2ZXJzaW9uIjoiNS42LjMiLCJsaWtlcyI6MzYxMSwicHVibGlzaGVySWQiOiJmaXJlYmFzZS5nb29nbGUuY29tIiwiaXNEaXNjb250aW51ZWQiOmZhbHNlLCJpc0xhdGVzdCI6dHJ1ZX0sInNlc3Npb25Bd2FyZSI6ZmFsc2V9"/><link rel="preload" href="/static/hash-8pjab7lp/highlight/highlight-with-init.js" as="script"/></head><body class="light-theme"><script src="/static/hash-8pjab7lp/js/dark-init.js"></script><noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MX6DBN9" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript><div class="site-header"><button class="hamburger" aria-label="menu toggle"></button><a class="logo" href="/" aria-label="Go to the landing page of pub.dev"><img class="site-logo" src="/static/hash-8pjab7lp/img/pub-dev-logo.svg" alt="" width="140" height="30" role="presentation"/></a><div class="site-header-space"></div><div class="site-header-mask"></div><div class="site-header-search"><form action="/packages" method="GET"><input class="site-header-search-input" name="q" placeholder="New search..." autocomplete="on" title="Search"/></form></div><nav class="site-header-nav scroll-container"><div class="nav-login-container"><button id="-account-login" class="nav-main-button link">Sign in</button></div><div class="nav-container nav-help-container hoverable"><button class="nav-main-button">Help</button><div class="nav-hover-popup"><div class="nav-table-columns"><div class="nav-table-column"><h3>pub.dev</h3><a class="nav-link" href="/help/search" rel="noopener" target="_blank">Searching for packages</a><a class="nav-link" href="/help/scoring" rel="noopener" target="_blank">Package scoring and pub points</a></div><div class="nav-table-column"><h3>Flutter</h3><a class="nav-link" href="https://flutter.dev/using-packages/" rel="noopener" target="_blank">Using packages</a><a class="nav-link" href="https://flutter.dev/developing-packages/" rel="noopener" target="_blank">Developing packages and plugins</a><a class="nav-link" href="https://dart.dev/tools/pub/publishing" rel="noopener" target="_blank">Publishing a package</a></div><div class="nav-table-column"><h3>Dart</h3><a class="nav-link" href="https://dart.dev/guides/packages" rel="noopener" target="_blank">Using packages</a><a class="nav-link" href="https://dart.dev/tools/pub/publishing" rel="noopener" target="_blank">Publishing a package</a></div></div></div></div><div class="nav-container nav-help-container-mobile foldable"><h3 class="foldable-button">pub.dev <img class="foldable-icon" src="/static/hash-8pjab7lp/img/nav-mobile-foldable-icon.svg" alt="toggle folding of the section" width="13" height="6"/></h3><div class="foldable-content"><a class="nav-link" href="/help/search" rel="noopener" target="_blank">Searching for packages</a><a class="nav-link" href="/help/scoring" rel="noopener" target="_blank">Package scoring and pub points</a></div></div><div class="nav-container nav-help-container-mobile foldable"><h3 class="foldable-button">Flutter <img class="foldable-icon" src="/static/hash-8pjab7lp/img/nav-mobile-foldable-icon.svg" alt="toggle folding of the section" width="13" height="6"/></h3><div class="foldable-content"><a class="nav-link" href="https://flutter.dev/using-packages/" rel="noopener" target="_blank">Using packages</a><a class="nav-link" href="https://flutter.dev/developing-packages/" rel="noopener" target="_blank">Developing packages and plugins</a><a class="nav-link" href="https://dart.dev/tools/pub/publishing" rel="noopener" target="_blank">Publishing a package</a></div></div><div class="nav-container nav-help-container-mobile foldable"><h3 class="foldable-button">Dart <img class="foldable-icon" src="/static/hash-8pjab7lp/img/nav-mobile-foldable-icon.svg" alt="toggle folding of the section" width="13" height="6"/></h3><div class="foldable-content"><a class="nav-link" href="https://dart.dev/guides/packages" rel="noopener" target="_blank">Using packages</a><a class="nav-link" href="https://dart.dev/tools/pub/publishing" rel="noopener" target="_blank">Publishing a package</a></div></div></nav><button class="-pub-theme-toggle" aria-label="light/dark theme toggle"></button></div><div id="banner-container"></div><main class="container"><div class="detail-wrapper -active -has-info-box"><div class="detail-banners"><a href="https://flutter.dev/docs/development/packages-and-plugins/favorites" rel="noopener" target="_blank" title="Package is a Flutter Favorite"><img class="ff-banner ff-banner-desktop displayed-in-light-theme" src="/static/hash-8pjab7lp/img/ff-banner-desktop-2x.png" alt="" width="150" height="218" role="presentation"/><img class="ff-banner ff-banner-desktop displayed-in-dark-theme" src="/static/hash-8pjab7lp/img/ff-banner-desktop-dark-2x.png" alt="" width="150" height="218" role="presentation"/><img class="ff-banner ff-banner-mobile displayed-in-light-theme" src="/static/hash-8pjab7lp/img/ff-banner-mobile-2x.png" alt="" width="94" height="116" role="presentation"/><img class="ff-banner ff-banner-mobile displayed-in-dark-theme" src="/static/hash-8pjab7lp/img/ff-banner-mobile-dark-2x.png" alt="" width="94" height="116" role="presentation"/></a></div><div class="detail-header -is-loose"><div class="detail-container"><div class="detail-header-outer-block"><div class="detail-header-content-block"><h1 class="title">cloud_firestore 5.6.3 <span class="pkg-page-title-copy"><img class="pub-monochrome-icon pkg-page-title-copy-icon filter-invert-on-dark" src="/static/hash-8pjab7lp/img/content-copy-icon.svg" alt="copy &quot;cloud_firestore: ^5.6.3&quot; to clipboard" width="18" height="18" title="Copy &quot;cloud_firestore: ^5.6.3&quot; to clipboard" data-copy-content="cloud_firestore: ^5.6.3" data-ga-click-event="copy-package-version"/><div class="pkg-page-title-copy-feedback"><span class="code">cloud_firestore: ^5.6.3</span> copied to clipboard</div></span></h1><div class="metadata">Published <span><a class="-x-ago" href="" title="Feb 5, 2025" role="button" data-timestamp="1738774394188">12 days ago</a></span> • <a class="-pub-publisher" href="/publishers/firebase.google.com"><img class="-pub-publisher-shield filter-invert-on-dark" src="/static/hash-8pjab7lp/img/material-icon-verified.svg" alt="verified publisher" width="14" height="14" title="Published by a pub.dev verified publisher"/>firebase.google.com</a><span class="package-badge" title="Package is compatible with Dart 3.">Dart 3 compatible</span></div><div class="detail-tags-and-like"><div class="detail-tags"><div class="-pub-tag-badge"><span class="tag-badge-main">SDK</span><a class="tag-badge-sub" href="/packages?q=sdk%3Aflutter" rel="nofollow" title="Packages compatible with Flutter SDK">Flutter</a></div><div class="-pub-tag-badge"><span class="tag-badge-main">Platform</span><a class="tag-badge-sub" href="/packages?q=platform%3Aandroid" rel="nofollow" title="Packages compatible with Android platform">Android</a><a class="tag-badge-sub" href="/packages?q=platform%3Aios" rel="nofollow" title="Packages compatible with iOS platform">iOS</a><a class="tag-badge-sub" href="/packages?q=platform%3Amacos" rel="nofollow" title="Packages compatible with macOS platform">macOS</a><a class="tag-badge-sub" href="/packages?q=platform%3Aweb" rel="nofollow" title="Packages compatible with Web platform">web</a><a class="tag-badge-sub" href="/packages?q=platform%3Awindows" rel="nofollow" title="Packages compatible with Windows platform">Windows</a></div></div><div class="detail-like"><button id="-pub-like-icon-button" class="mdc-icon-button" data-ga-click-event="toggle-like" aria-pressed="false" title="Like this package"><img class="mdc-icon-button__icon" src="/static/hash-8pjab7lp/img/like-inactive.svg" alt="liked status: inactive" width="18" height="18"/><img class="mdc-icon-button__icon mdc-icon-button__icon--on" src="/static/hash-8pjab7lp/img/like-active.svg" alt="liked status: active" width="18" height="18"/></button><span class="likes-count"><span id="likes-count">3.6k</span></span></div></div></div></div></div></div><div class="detail-container"><div class="detail-lead"><div class="detail-metadata-toggle"><div class="detail-metadata-toggle-icon">→</div><h3 class="detail-lead-title">Metadata</h3></div><p class="detail-lead-text">Flutter plugin for Cloud Firestore, a cloud-hosted, noSQL database with live synchronization and offline support on Android and iOS.</p><p class="detail-lead-more"><a class="detail-metadata-toggle">More...</a></p></div></div><div class="detail-body"><div class="detail-tabs"><div class="detail-tabs-wide-header"><div class="detail-container"><ul class="detail-tabs-header"><li class="detail-tab tab-link detail-tab-readme-title"><a href="/packages/cloud_firestore" role="button">Readme</a></li><li class="detail-tab tab-link detail-tab-changelog-title"><a href="/packages/cloud_firestore/changelog" role="button">Changelog</a></li><li class="detail-tab tab-button detail-tab-example-title -active">Example</li><li class="detail-tab tab-link detail-tab-installing-title"><a href="/packages/cloud_firestore/install" role="button">Installing</a></li><li class="detail-tab tab-link detail-tab-versions-title"><a href="/packages/cloud_firestore/versions" role="button">Versions</a></li><li class="detail-tab tab-link detail-tab-analysis-title"><a href="/packages/cloud_firestore/score" role="button">Scores</a></li></ul></div></div><div class="detail-container detail-body-main"><div class="detail-tabs-content"><section class="tab-content detail-tab-example-content -active markdown-body"><p style="font-family: monospace"><b><a href="https://github.com/firebase/flutterfire/blob/main/packages/cloud_firestore/cloud_firestore/example/lib/main.dart" rel="noopener noreferrer nofollow" target="_blank">example&#47;lib&#47;main.dart</a></b></p><pre><code class="language-dart">&#47;&#47; Copyright 2020, the Chromium project authors. Please see the AUTHORS file &#47;&#47; for details. All rights reserved. Use of this source code is governed by a &#47;&#47; BSD-style license that can be found in the LICENSE file. import &#39;dart:async&#39;; import &#39;package:cloud_firestore&#47;cloud_firestore.dart&#39;; import &#39;package:firebase_core&#47;firebase_core.dart&#39;; import &#39;package:flutter&#47;foundation.dart&#39;; import &#39;package:flutter&#47;material.dart&#39;; import &#39;package:http&#47;http.dart&#39; as http; import &#39;firebase_options.dart&#39;; &#47;&#47;&#47; Requires that a Firestore emulator is running locally. &#47;&#47;&#47; See https:&#47;&#47;firebase.google.com&#47;docs&#47;firestore&#47;quickstart#optional_prototype_and_test_with bool shouldUseFirestoreEmulator = true; Future&lt;Uint8List&gt; loadBundleSetup(int number) async { &#47;&#47; endpoint serves a bundle with 3 documents each containing &#47;&#47; a &#39;number&#39; property that increments in value 1-3. final url = Uri.https(&#39;api.rnfirebase.io&#39;, &#39;&#47;firestore&#47;e2e-tests&#47;bundle-$number&#39;); final response = await http.get(url); String string = response.body; return Uint8List.fromList(string.codeUnits); } Future&lt;void&gt; main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); FirebaseFirestore.instance.settings = const Settings( persistenceEnabled: true, ); if (shouldUseFirestoreEmulator) { FirebaseFirestore.instance.useFirestoreEmulator(&#39;localhost&#39;, 8080); } runApp(FirestoreExampleApp()); } &#47;&#47;&#47; A reference to the list of movies. &#47;&#47;&#47; We are using `withConverter` to ensure that interactions with the collection &#47;&#47;&#47; are type-safe. final moviesRef = FirebaseFirestore.instance .collection(&#39;firestore-example-app&#39;) .withConverter&lt;Movie&gt;( fromFirestore: (snapshots, _) =&gt; Movie.fromJson(snapshots.data()!), toFirestore: (movie, _) =&gt; movie.toJson(), ); &#47;&#47;&#47; The different ways that we can filter&#47;sort movies. enum MovieQuery { year, likesAsc, likesDesc, rated, sciFi, fantasy, } extension on Query&lt;Movie&gt; { &#47;&#47;&#47; Create a firebase query from a [MovieQuery] Query&lt;Movie&gt; queryBy(MovieQuery query) { return switch (query) { MovieQuery.fantasy =&gt; where(&#39;genre&#39;, arrayContainsAny: [&#39;fantasy&#39;]), MovieQuery.sciFi =&gt; where(&#39;genre&#39;, arrayContainsAny: [&#39;sci-fi&#39;]), MovieQuery.likesAsc || MovieQuery.likesDesc =&gt; orderBy(&#39;likes&#39;, descending: query == MovieQuery.likesDesc), MovieQuery.year =&gt; orderBy(&#39;year&#39;, descending: true), MovieQuery.rated =&gt; orderBy(&#39;rated&#39;, descending: true) }; } } &#47;&#47;&#47; The entry point of the application. &#47;&#47;&#47; &#47;&#47;&#47; Returns a [MaterialApp]. class FirestoreExampleApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: &#39;Firestore Example App&#39;, theme: ThemeData.dark(), home: const Scaffold( body: Center(child: FilmList()), ), ); } } &#47;&#47;&#47; Holds all example app films class FilmList extends StatefulWidget { const FilmList({Key? key}) : super(key: key); @override _FilmListState createState() =&gt; _FilmListState(); } class _FilmListState extends State&lt;FilmList&gt; { MovieQuery query = MovieQuery.year; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text(&#39;Firestore Example: Movies&#39;), &#47;&#47; This is a example use for &#39;snapshots in sync&#39;. &#47;&#47; The view reflects the time of the last Firestore sync; which happens any time a field is updated. StreamBuilder( stream: FirebaseFirestore.instance.snapshotsInSync(), builder: (context, _) { return Text( &#39;Latest Snapshot: ${DateTime.now()}&#39;, style: Theme.of(context).textTheme.bodySmall, ); }, ), ], ), actions: &lt;Widget&gt;[ PopupMenuButton&lt;MovieQuery&gt;( onSelected: (value) =&gt; setState(() =&gt; query = value), icon: const Icon(Icons.sort), itemBuilder: (BuildContext context) { return [ const PopupMenuItem( value: MovieQuery.year, child: Text(&#39;Sort by Year&#39;), ), const PopupMenuItem( value: MovieQuery.rated, child: Text(&#39;Sort by Rated&#39;), ), const PopupMenuItem( value: MovieQuery.likesAsc, child: Text(&#39;Sort by Likes ascending&#39;), ), const PopupMenuItem( value: MovieQuery.likesDesc, child: Text(&#39;Sort by Likes descending&#39;), ), const PopupMenuItem( value: MovieQuery.fantasy, child: Text(&#39;Filter genre fantasy&#39;), ), const PopupMenuItem( value: MovieQuery.sciFi, child: Text(&#39;Filter genre sci-fi&#39;), ), ]; }, ), PopupMenuButton&lt;String&gt;( onSelected: (value) async { switch (value) { case &#39;reset_likes&#39;: return _resetLikes(); case &#39;aggregate&#39;: &#47;&#47; Count the number of movies final _count = await FirebaseFirestore.instance .collection(&#39;firestore-example-app&#39;) .count() .get(); print(&#39;Count: ${_count.count}&#39;); &#47;&#47; Average the number of likes final _average = await FirebaseFirestore.instance .collection(&#39;firestore-example-app&#39;) .aggregate(average(&#39;likes&#39;)) .get(); print(&#39;Average: ${_average.getAverage(&#39;likes&#39;)}&#39;); &#47;&#47; Sum the number of likes final _sum = await FirebaseFirestore.instance .collection(&#39;firestore-example-app&#39;) .aggregate(sum(&#39;likes&#39;)) .get(); print(&#39;Sum: ${_sum.getSum(&#39;likes&#39;)}&#39;); &#47;&#47; In one query final _all = await FirebaseFirestore.instance .collection(&#39;firestore-example-app&#39;) .aggregate( average(&#39;likes&#39;), sum(&#39;likes&#39;), count(), ) .get(); print(&#39;Average: ${_all.getAverage(&#39;likes&#39;)} &#39; &#39;Sum: ${_all.getSum(&#39;likes&#39;)} &#39; &#39;Count: ${_all.count}&#39;); return; case &#39;load_bundle&#39;: Uint8List buffer = await loadBundleSetup(2); LoadBundleTask task = FirebaseFirestore.instance.loadBundle(buffer); final list = await task.stream.toList(); print( list.map((e) =&gt; e.totalDocuments), ); print( list.map((e) =&gt; e.bytesLoaded), ); print( list.map((e) =&gt; e.documentsLoaded), ); print( list.map((e) =&gt; e.totalBytes), ); print( list, ); LoadBundleTaskSnapshot lastSnapshot = list.removeLast(); print(lastSnapshot.taskState); print( list.map((e) =&gt; e.taskState), ); return; case &#39;vectorValue&#39;: const vectorValue = VectorValue([1.0, 2.0, 3.0]); final vectorValueDoc = await FirebaseFirestore.instance .collection(&#39;firestore-example-app&#39;) .add({&#39;vectorValue&#39;: vectorValue}); final snapshot = await vectorValueDoc.get(); print(snapshot.data()); return; default: return; } }, itemBuilder: (BuildContext context) { return [ const PopupMenuItem( value: &#39;reset_likes&#39;, child: Text(&#39;Reset like counts (WriteBatch)&#39;), ), const PopupMenuItem( value: &#39;aggregate&#39;, child: Text(&#39;Get aggregate data&#39;), ), const PopupMenuItem( value: &#39;load_bundle&#39;, child: Text(&#39;Load bundle&#39;), ), const PopupMenuItem( value: &#39;vectorValue&#39;, child: Text(&#39;Test Vector Value&#39;), ), ]; }, ), ], ), body: StreamBuilder&lt;QuerySnapshot&lt;Movie&gt;&gt;( stream: moviesRef.queryBy(query).snapshots(), builder: (context, snapshot) { if (snapshot.hasError) { return Center( child: Text(snapshot.error.toString()), ); } if (!snapshot.hasData) { return const Center(child: CircularProgressIndicator()); } final data = snapshot.requireData; return ListView.builder( itemCount: data.size, itemBuilder: (context, index) { return _MovieItem( data.docs[index].data(), data.docs[index].reference, ); }, ); }, ), ); } Future&lt;void&gt; _resetLikes() async { final movies = await moviesRef.get( const GetOptions( serverTimestampBehavior: ServerTimestampBehavior.previous, ), ); WriteBatch batch = FirebaseFirestore.instance.batch(); for (final movie in movies.docs) { batch.update(movie.reference, {&#39;likes&#39;: 0}); } await batch.commit(); } } &#47;&#47;&#47; A single movie row. class _MovieItem extends StatelessWidget { _MovieItem(this.movie, this.reference); final Movie movie; final DocumentReference&lt;Movie&gt; reference; &#47;&#47;&#47; Returns the movie poster. Widget get poster { return SizedBox( width: 100, child: Image.network(movie.poster), ); } &#47;&#47;&#47; Returns movie details. Widget get details { return Padding( padding: const EdgeInsets.only(left: 8, right: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ title, metadata, genres, Likes( reference: reference, currentLikes: movie.likes, ), ], ), ); } &#47;&#47;&#47; Return the movie title. Widget get title { return Text( &#39;${movie.title} (${movie.year})&#39;, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ); } &#47;&#47;&#47; Returns metadata about the movie. Widget get metadata { return Padding( padding: const EdgeInsets.only(top: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(right: 8), child: Text(&#39;Rated: ${movie.rated}&#39;), ), Text(&#39;Runtime: ${movie.runtime}&#39;), ], ), ); } &#47;&#47;&#47; Returns a list of genre movie tags. List&lt;Widget&gt; get genreItems { return [ for (final genre in movie.genre) Padding( padding: const EdgeInsets.only(right: 2), child: Chip( backgroundColor: Colors.lightBlue, label: Text( genre, style: const TextStyle(color: Colors.white), ), ), ), ]; } &#47;&#47;&#47; Returns all genres. Widget get genres { return Padding( padding: const EdgeInsets.only(top: 8), child: Wrap( children: genreItems, ), ); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(bottom: 4, top: 4), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ poster, Flexible(child: details), ], ), ); } } &#47;&#47;&#47; Displays and manages the movie &#39;like&#39; count. class Likes extends StatefulWidget { &#47;&#47;&#47; Constructs a new [Likes] instance with a given [DocumentReference] and &#47;&#47;&#47; current like count. Likes({ Key? key, required this.reference, required this.currentLikes, }) : super(key: key); &#47;&#47;&#47; The reference relating to the counter. final DocumentReference&lt;Movie&gt; reference; &#47;&#47;&#47; The number of current likes (before manipulation). final int currentLikes; @override _LikesState createState() =&gt; _LikesState(); } class _LikesState extends State&lt;Likes&gt; { &#47;&#47;&#47; A local cache of the current likes, used to immediately render the updated &#47;&#47;&#47; likes count after an update, even while the request isn&#39;t completed yet. late int _likes = widget.currentLikes; Future&lt;void&gt; _onLike() async { final currentLikes = _likes; &#47;&#47; Increment the &#39;like&#39; count straight away to show feedback to the user. setState(() { _likes = currentLikes + 1; }); try { &#47;&#47; Update the likes using a transaction. &#47;&#47; We use a transaction because multiple users could update the likes count &#47;&#47; simultaneously. As such, our likes count may be different from the likes &#47;&#47; count on the server. int newLikes = await FirebaseFirestore.instance .runTransaction&lt;int&gt;((transaction) async { DocumentSnapshot&lt;Movie&gt; movie = await transaction.get&lt;Movie&gt;(widget.reference); if (!movie.exists) { throw Exception(&#39;Document does not exist!&#39;); } int updatedLikes = movie.data()!.likes + 1; transaction.update(widget.reference, {&#39;likes&#39;: updatedLikes}); return updatedLikes; }); &#47;&#47; Update with the real count once the transaction has completed. setState(() =&gt; _likes = newLikes); } catch (e, s) { print(s); print(&#39;Failed to update likes for document! $e&#39;); &#47;&#47; If the transaction fails, revert back to the old count setState(() =&gt; _likes = currentLikes); } } @override void didUpdateWidget(Likes oldWidget) { super.didUpdateWidget(oldWidget); &#47;&#47; The likes on the server changed, so we need to update our local cache to &#47;&#47; keep things in sync. Otherwise if another user updates the likes, &#47;&#47; we won&#39;t see the update. if (widget.currentLikes != oldWidget.currentLikes) { _likes = widget.currentLikes; } } @override Widget build(BuildContext context) { return Row( children: [ IconButton( iconSize: 20, onPressed: _onLike, icon: const Icon(Icons.favorite), ), Text(&#39;$_likes likes&#39;), ], ); } } @immutable class Movie { Movie({ required this.genre, required this.likes, required this.poster, required this.rated, required this.runtime, required this.title, required this.year, }); Movie.fromJson(Map&lt;String, Object?&gt; json) : this( genre: (json[&#39;genre&#39;]! as List).cast&lt;String&gt;(), likes: json[&#39;likes&#39;]! as int, poster: json[&#39;poster&#39;]! as String, rated: json[&#39;rated&#39;]! as String, runtime: json[&#39;runtime&#39;]! as String, title: json[&#39;title&#39;]! as String, year: json[&#39;year&#39;]! as int, ); final String poster; final int likes; final String title; final int year; final String runtime; final String rated; final List&lt;String&gt; genre; Map&lt;String, Object?&gt; toJson() { return { &#39;genre&#39;: genre, &#39;likes&#39;: likes, &#39;poster&#39;: poster, &#39;rated&#39;: rated, &#39;runtime&#39;: runtime, &#39;title&#39;: title, &#39;year&#39;: year, }; } }</code></pre></section></div></div></div><aside class="detail-info-box"><a class="packages-scores" href="/packages/cloud_firestore/score"><div class="packages-score packages-score-like"><div class="packages-score-value -has-value"><span class="packages-score-value-number">3.61k</span><span class="packages-score-value-sign"></span></div><div class="packages-score-label">likes</div></div><div class="packages-score packages-score-health"><div class="packages-score-value -has-value"><span class="packages-score-value-number">160</span><span class="packages-score-value-sign"></span></div><div class="packages-score-label">points</div></div><div class="packages-score packages-score-downloads" title="Number of downloads of this package during the past 30 days"><div class="packages-score-value -has-value"><span class="packages-score-value-number">759k</span><span class="packages-score-value-sign"></span></div><div class="packages-score-label">downloads</div></div></a><h3 class="title">Publisher</h3><p><a href="/publishers/firebase.google.com"><img class="-pub-publisher-shield filter-invert-on-dark" src="/static/hash-8pjab7lp/img/material-icon-verified.svg" alt="verified publisher" width="14" height="14" title="Published by a pub.dev verified publisher"/>firebase.google.com</a></p><h3 class="title">Weekly Downloads</h3><div id="-weekly-downloads-sparkline" class="weekly-downloads-sparkline" data-widget="weekly-sparkline" data-weekly-sparkline-points="ANmvZ4jrAgBIwwIAN48CANm7AgBurgIAraMCAC2gAQAppgEAMMUCAF+cAgCvegIAa3oCAFy/AgC11AIAJ6MCACyfAgAHswIAh5UCAIGoAgD70AIA6vUCAA2eAgBGmwIA18ECAOCiAgCGnwIAZowCAHPAAgDscQIAOXYCAEFXAgBJfgIAyiACAPxoAgB/QAIA+KkCAIqFAgBMsQIAHLMCAImXAgBnWwIAWxkCADCXAgBuwgIAxJMCAMUcAwAFqgIAyQ8DAIAyAwAcfgMAYDADABKPAwA="></div><h3 class="title pkg-infobox-metadata">Metadata</h3><p>Flutter plugin for Cloud Firestore, a cloud-hosted, noSQL database with live synchronization and offline support on Android and iOS.</p><p><a class="link" href="https://firebase.google.com/docs/firestore" rel="ugc">Homepage</a><br/><a class="link" href="https://github.com/firebase/flutterfire/tree/main/packages/cloud_firestore/cloud_firestore" rel="ugc">Repository (GitHub)</a><br/><a class="link" href="https://github.com/firebase/flutterfire/blob/main/CONTRIBUTING.md" rel="ugc">Contributing</a><br/></p><h3 class="title">Topics</h3><p><a class="topics-tag" href="/packages?q=topic%3Afirebase" rel="nofollow">#firebase</a> <a class="topics-tag" href="/packages?q=topic%3Afirestore" rel="nofollow">#firestore</a> <a class="topics-tag" href="/packages?q=topic%3Arealtime" rel="nofollow">#realtime</a> <a class="topics-tag" href="/packages?q=topic%3Adatabase" rel="nofollow">#database</a></p><h3 class="title">Documentation</h3><p><a class="link" href="/documentation/cloud_firestore/latest/">API reference</a><br/></p><h3 class="title">License</h3><p><img class="inline-icon-img filter-invert-on-dark" src="/static/hash-8pjab7lp/img/material-icon-balance.svg" alt="" width="14" height="14" role="presentation"/>BSD-3-Clause (<a href="/packages/cloud_firestore/license">license</a>)</p><h3 class="title">Dependencies</h3><p><a href="/packages/cloud_firestore_platform_interface" title="^6.6.3">cloud_firestore_platform_interface</a>, <a href="/packages/cloud_firestore_web" title="^4.4.3">cloud_firestore_web</a>, <a href="/packages/collection" title="^1.0.0">collection</a>, <a href="/packages/firebase_core" title="^3.11.0">firebase_core</a>, <a href="/packages/firebase_core_platform_interface" title="^5.4.0">firebase_core_platform_interface</a>, <a href="https://api.flutter.dev/">flutter</a>, <a href="/packages/meta" title="^1.8.0">meta</a></p><h3 class="title">More</h3><p><a href="/packages?q=dependency%3Acloud_firestore" rel="nofollow">Packages that depend on cloud_firestore</a></p></aside></div><script type="application/ld+json">{"@context":"http\u003a\u002f\u002fschema.org","@type":"SoftwareSourceCode","name":"cloud\u005ffirestore","version":"5.6.3","description":"cloud\u005ffirestore - Flutter plugin for Cloud Firestore, a cloud-hosted, noSQL database with live synchronization and offline support on Android and iOS.","url":"https\u003a\u002f\u002fpub.dev\u002fpackages\u002fcloud\u005ffirestore","dateCreated":"2017-10-27T22\u003a53\u003a13.312411Z","dateModified":"2025-02-05T16\u003a53\u003a14.188376Z","programmingLanguage":"Dart","image":"https\u003a\u002f\u002fpub.dev\u002fstatic\u002fimg\u002fpub-dev-icon-cover-image.png","license":"https\u003a\u002f\u002fpub.dev\u002fpackages\u002fcloud\u005ffirestore\u002flicense"}</script></div><div class="detail-metadata"><h3 class="detail-metadata-title"><span class="detail-metadata-toggle">←</span> Metadata</h3><div class="detail-info-box"><a class="packages-scores" href="/packages/cloud_firestore/score"><div class="packages-score packages-score-like"><div class="packages-score-value -has-value"><span class="packages-score-value-number">3.61k</span><span class="packages-score-value-sign"></span></div><div class="packages-score-label">likes</div></div><div class="packages-score packages-score-health"><div class="packages-score-value -has-value"><span class="packages-score-value-number">160</span><span class="packages-score-value-sign"></span></div><div class="packages-score-label">points</div></div><div class="packages-score packages-score-downloads" title="Number of downloads of this package during the past 30 days"><div class="packages-score-value -has-value"><span class="packages-score-value-number">759k</span><span class="packages-score-value-sign"></span></div><div class="packages-score-label">downloads</div></div></a><h3 class="title">Publisher</h3><p><a href="/publishers/firebase.google.com"><img class="-pub-publisher-shield filter-invert-on-dark" src="/static/hash-8pjab7lp/img/material-icon-verified.svg" alt="verified publisher" width="14" height="14" title="Published by a pub.dev verified publisher"/>firebase.google.com</a></p><h3 class="title">Weekly Downloads</h3><div id="-weekly-downloads-sparkline" class="weekly-downloads-sparkline" data-widget="weekly-sparkline" data-weekly-sparkline-points="ANmvZ4jrAgBIwwIAN48CANm7AgBurgIAraMCAC2gAQAppgEAMMUCAF+cAgCvegIAa3oCAFy/AgC11AIAJ6MCACyfAgAHswIAh5UCAIGoAgD70AIA6vUCAA2eAgBGmwIA18ECAOCiAgCGnwIAZowCAHPAAgDscQIAOXYCAEFXAgBJfgIAyiACAPxoAgB/QAIA+KkCAIqFAgBMsQIAHLMCAImXAgBnWwIAWxkCADCXAgBuwgIAxJMCAMUcAwAFqgIAyQ8DAIAyAwAcfgMAYDADABKPAwA="></div><h3 class="title pkg-infobox-metadata">Metadata</h3><p>Flutter plugin for Cloud Firestore, a cloud-hosted, noSQL database with live synchronization and offline support on Android and iOS.</p><p><a class="link" href="https://firebase.google.com/docs/firestore" rel="ugc">Homepage</a><br/><a class="link" href="https://github.com/firebase/flutterfire/tree/main/packages/cloud_firestore/cloud_firestore" rel="ugc">Repository (GitHub)</a><br/><a class="link" href="https://github.com/firebase/flutterfire/blob/main/CONTRIBUTING.md" rel="ugc">Contributing</a><br/></p><h3 class="title">Topics</h3><p><a class="topics-tag" href="/packages?q=topic%3Afirebase" rel="nofollow">#firebase</a> <a class="topics-tag" href="/packages?q=topic%3Afirestore" rel="nofollow">#firestore</a> <a class="topics-tag" href="/packages?q=topic%3Arealtime" rel="nofollow">#realtime</a> <a class="topics-tag" href="/packages?q=topic%3Adatabase" rel="nofollow">#database</a></p><h3 class="title">Documentation</h3><p><a class="link" href="/documentation/cloud_firestore/latest/">API reference</a><br/></p><h3 class="title">License</h3><p><img class="inline-icon-img filter-invert-on-dark" src="/static/hash-8pjab7lp/img/material-icon-balance.svg" alt="" width="14" height="14" role="presentation"/>BSD-3-Clause (<a href="/packages/cloud_firestore/license">license</a>)</p><h3 class="title">Dependencies</h3><p><a href="/packages/cloud_firestore_platform_interface" title="^6.6.3">cloud_firestore_platform_interface</a>, <a href="/packages/cloud_firestore_web" title="^4.4.3">cloud_firestore_web</a>, <a href="/packages/collection" title="^1.0.0">collection</a>, <a href="/packages/firebase_core" title="^3.11.0">firebase_core</a>, <a href="/packages/firebase_core_platform_interface" title="^5.4.0">firebase_core_platform_interface</a>, <a href="https://api.flutter.dev/">flutter</a>, <a href="/packages/meta" title="^1.8.0">meta</a></p><h3 class="title">More</h3><p><a href="/packages?q=dependency%3Acloud_firestore" rel="nofollow">Packages that depend on cloud_firestore</a></p></div><p class="detail-lead-back"><a class="detail-metadata-toggle">Back</a></p></div><div id="-screenshot-carousel" class="carousel"><fab id="-carousel-prev" class="mdc-fab carousel-prev carousel-nav" data-mdc-auto-init="MDCRipple" title="Previous" data-ga-click-event="screenshot-carousel-prev-click" tabindex="0"><div class="mdc-fab__ripple"></div><img class="mdc-fab__icon" src="/static/hash-8pjab7lp/img/keyboard_arrow_left.svg" alt="previous" width="24" height="24" aria-hidden="true"/></fab><div id="-image-container" class="image-container"></div><fab id="-carousel-next" class="mdc-fab carousel-next carousel-nav" data-mdc-auto-init="MDCRipple" title="Next" data-ga-click-event="screenshot-carousel-next-click" tabindex="0"><div class="mdc-fab__ripple"></div><img class="mdc-fab__icon" src="/static/hash-8pjab7lp/img/keyboard_arrow_right.svg" alt="next" width="24" height="24" aria-hidden="true"/></fab><p id="-screenshot-description" class="screenshot-description"></p></div></main><footer class="site-footer"><a class="link" href="https://dart.dev/">Dart language</a><a class="link sep" href="/report?subject=package%3Acloud_firestore&amp;url=https%3A%2F%2Fpub.dev%2Fpackages%2Fcloud_firestore%2Fexample">Report package</a><a class="link sep" href="/policy">Policy</a><a class="link sep" href="https://www.google.com/intl/en/policies/terms/">Terms</a><a class="link sep" href="https://developers.google.com/terms/">API Terms</a><a class="link sep" href="/security">Security</a><a class="link sep" href="https://www.google.com/intl/en/policies/privacy/">Privacy</a><a class="link sep" href="/help">Help</a><a class="link icon sep" href="/feed.atom"><img class="inline-icon" src="/static/hash-8pjab7lp/img/rss-feed-icon.svg" alt="RSS" width="20" height="20" title="RSS/atom feed"/></a><a class="link icon github_issue" href="https://github.com/dart-lang/pub-dev/issues/new"><img class="inline-icon" src="/static/hash-8pjab7lp/img/bug-report-white-96px.png" alt="bug report" width="20" height="20" title="Report an issue with this site"/></a></footer><script src="/static/hash-8pjab7lp/highlight/highlight-with-init.js" defer="defer"></script></body></html>

Pages: 1 2 3 4 5 6 7 8 9 10