-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Refactor Dart counter sample to use shared package #1267
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jhuleatt
merged 1 commit into
codelab-dart
from
dart-counter-shared-refactor-16206636299737686696
Apr 10, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
130 changes: 48 additions & 82 deletions
130
Dart/quickstarts/https-increment-number/bin/server.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,99 +1,65 @@ | ||
| import 'dart:convert'; | ||
| import 'package:dart_firebase_admin/dart_firebase_admin.dart'; | ||
| import 'package:firebase_functions/firebase_functions.dart'; | ||
| import 'package:google_cloud_firestore/google_cloud_firestore.dart'; | ||
|
|
||
| class IncrementResponse { | ||
| final String message; | ||
| final int newCount; | ||
|
|
||
| IncrementResponse({required this.message, required this.newCount}); | ||
|
|
||
| Map<String, dynamic> toJson() => {'message': message, 'newCount': newCount}; | ||
| } | ||
| import 'package:google_cloud_firestore/google_cloud_firestore.dart' | ||
| show FieldValue; | ||
| import 'package:shared/shared.dart'; | ||
|
|
||
| void main(List<String> args) async { | ||
| await fireUp(args, (firebase) { | ||
| // [START dartHttpIncrementLocal] | ||
| firebase.https.onRequest(name: 'incrementLocal', (request) async { | ||
| print('Incrementing counter locally...'); | ||
|
|
||
| if (request.method != 'POST') { | ||
| return Response(405, body: 'Method Not Allowed'); | ||
| } | ||
|
|
||
| int currentCount = 0; | ||
| final bodyString = await request.readAsString(); | ||
| if (bodyString.isNotEmpty) { | ||
| try { | ||
| final body = jsonDecode(bodyString) as Map<String, dynamic>; | ||
| currentCount = body['count'] as int? ?? 0; | ||
| } catch (e) { | ||
| return Response.badRequest(body: 'Invalid JSON request'); | ||
| } | ||
| } | ||
|
|
||
| final response = IncrementResponse( | ||
| message: 'Local increment complete!', | ||
| newCount: currentCount + 1, | ||
| ); | ||
|
|
||
| return Response( | ||
| 200, | ||
| body: jsonEncode(response.toJson()), | ||
| headers: {'Content-Type': 'application/json'}, | ||
| ); | ||
| }); | ||
| // [END dartHttpIncrementLocal] | ||
| // Listen for calls to the http request and name defined in the shared package. | ||
| firebase.https.onRequest(name: incrementCallable, (request) async { | ||
| // In a production app, verify the user with request.auth?.uid here. | ||
| print('Incrementing counter on the server...'); | ||
|
|
||
| // [START dartHttpIncrementSynced] | ||
| firebase.https.onRequest(name: 'incrementSynced', (request) async { | ||
| print('Processing synced counter request...'); | ||
|
|
||
| // Get firestore admin instance | ||
| final firestore = FirebaseApp.instance.firestore(); | ||
| // Get firestore database instance | ||
| final firestore = firebase.adminApp.firestore(); | ||
|
|
||
| // Get a reference to the counter document | ||
| final counterDoc = firestore.collection('counters').doc('global'); | ||
|
|
||
| // Fetch the current counter value | ||
| // Get the current snapshot for the count data | ||
| final snapshot = await counterDoc.get(); | ||
| final currentCount = snapshot.data()?['count'] as int? ?? 0; | ||
|
|
||
| if (request.method == 'GET') { | ||
| // Handle GET request to respond with the current counter | ||
| final response = IncrementResponse( | ||
| message: 'Cloud-sync fetched!', | ||
| newCount: currentCount, | ||
| ); | ||
|
|
||
| return Response( | ||
| 200, | ||
| body: jsonEncode(response.toJson()), | ||
| headers: {'Content-Type': 'application/json'}, | ||
| ); | ||
| } else if (request.method == 'POST') { | ||
| // Handle POST request to increment the counter | ||
|
|
||
| // Increment count by one | ||
| await counterDoc.set({ | ||
| 'count': FieldValue.increment(1), | ||
| }, options: SetOptions.merge()); | ||
|
|
||
| final response = IncrementResponse( | ||
| message: 'Cloud-sync complete!', | ||
| newCount: currentCount + 1, | ||
| ); | ||
|
|
||
| return Response( | ||
| 200, | ||
| body: jsonEncode(response.toJson()), | ||
| headers: {'Content-Type': 'application/json'}, | ||
| ); | ||
| // Increment response we will send back | ||
| IncrementResponse incrementResponse; | ||
|
|
||
| // Check for the current count and if the snapshot exists | ||
| if (snapshot.data() case {'count': int value} when snapshot.exists) { | ||
| if (request.method == 'GET') { | ||
| // Get the current result | ||
| incrementResponse = IncrementResponse( | ||
| success: true, | ||
| message: 'Read-only sync complete', | ||
| newCount: value, | ||
| ); | ||
| } else if (request.method == 'POST') { | ||
| // Increment count by one | ||
| final step = request.url.queryParameters['step'] as int? ?? 1; | ||
| await counterDoc.update({'count': FieldValue.increment(step)}); | ||
| incrementResponse = IncrementResponse( | ||
| success: true, | ||
| message: 'Atomic increment complete', | ||
| newCount: value + 1, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| ); | ||
| } else { | ||
| return Response(405, body: 'Method Not Allowed'); | ||
| } | ||
| } else { | ||
| return Response(405, body: 'Method Not Allowed'); | ||
| // Create a new document with a count of 1 | ||
| await counterDoc.set({'count': 1}); | ||
| incrementResponse = const IncrementResponse( | ||
| success: true, | ||
| message: 'Cloud-sync complete', | ||
| newCount: 1, | ||
| ); | ||
| } | ||
|
|
||
| // Return the response as JSON | ||
| return Response( | ||
| 200, | ||
| body: jsonEncode(incrementResponse.toJson()), | ||
| headers: {'Content-Type': 'application/json'}, | ||
| ); | ||
| }); | ||
| // [END dartHttpIncrementSynced] | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| .dart_tool/ | ||
| .packages | ||
| build/ | ||
| *.dart_tool | ||
| pubspec.lock |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| class IncrementResponse { | ||
| final bool success; | ||
| final String message; | ||
| final int newCount; | ||
|
|
||
| const IncrementResponse({ | ||
| required this.success, | ||
| required this.message, | ||
| required this.newCount, | ||
| }); | ||
|
|
||
| Map<String, dynamic> toJson() => { | ||
| 'success': success, | ||
| 'message': message, | ||
| 'newCount': newCount, | ||
| }; | ||
| } | ||
|
|
||
| const String incrementCallable = 'incrementSynced'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| name: shared | ||
| description: Shared classes. | ||
| publish_to: none | ||
|
|
||
| environment: | ||
| sdk: ^3.11.0 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The cast
as int?will cause a runtimeTypeErrorbecauserequest.url.queryParametersreturns aMap<String, String>. You should useint.tryParseto safely convert the string value to an integer.