text
stringlengths
1
474
throw FirebaseControllerException(
'Failed to parse data from Firestore: $e');
}
}
/// Takes a list of [PlayingCard]s and converts it into a JSON object
/// that can be saved into Firestore.
Map<String, Object?> _cardsToFirestore(
List<PlayingCard> cards,
SetOptions? options,
) {
return {'cards': cards.map((c) => c.toJson()).toList()};
}
/// Updates Firestore with the local state of [area].
Future<void> _updateFirestoreFromLocal(
PlayingArea area, DocumentReference<List<PlayingCard>> ref) async {
try {
_log.fine('Updating Firestore with local data (${area.cards}) ...');
await ref.set(area.cards);
_log.fine('... done updating.');
} catch (e) {
throw FirebaseControllerException(
'Failed to update Firestore with local data (${area.cards}): $e');
}
}
/// Sends the local state of `boardState.areaOne` to Firestore.
void _updateFirestoreFromLocalAreaOne() {
_updateFirestoreFromLocal(boardState.areaOne, _areaOneRef);
}
/// Sends the local state of `boardState.areaTwo` to Firestore.
void _updateFirestoreFromLocalAreaTwo() {
_updateFirestoreFromLocal(boardState.areaTwo, _areaTwoRef);
}
/// Updates the local state of [area] with the data from Firestore.
void _updateLocalFromFirestore(
PlayingArea area, DocumentSnapshot<List<PlayingCard>> snapshot) {
_log.fine('Received new data from Firestore (${snapshot.data()})');
final cards = snapshot.data() ?? [];
if (listEquals(cards, area.cards)) {
_log.fine('No change');
} else {
_log.fine('Updating local data with Firestore data ($cards)');
area.replaceWith(cards);
}
}
}
class FirebaseControllerException implements Exception {
final String message;
FirebaseControllerException(this.message);
@override
String toString() => 'FirebaseControllerException: $message';
}<code_end>
Notice the following features of this code:The controller’s constructor takes a BoardState.
This enables the controller to manipulate the local state of the game.The controller subscribes to both local changes to update Firestore
and to remote changes to update the local state and UI.The fields _areaOneRef and _areaTwoRef are
Firebase document references.
They describe where the data for each area resides,
and how to convert between the local Dart objects (List<PlayingCard>)
and remote JSON objects (Map<String, dynamic>).
The Firestore API lets us subscribe to these references
with .snapshots(), and write to them with .set().<topic_end>
<topic_start>
5. Use the Firestore controller
Open the file responsible for starting the play session:
lib/play_session/play_session_screen.dart in the case of the
card template.
You instantiate the Firestore controller from this file.Import Firebase and the controller:
<code_start>import 'package:cloud_firestore/cloud_firestore.dart';
import '../multiplayer/firestore_controller.dart';<code_end>
Add a nullable field to the _PlaySessionScreenState class
to contain a controller instance:
<code_start>FirestoreController? _firestoreController;<code_end>
In the initState() method of the same class,
add code that tries to read the FirebaseFirestore instance
and, if successful, constructs the controller.
You added the FirebaseFirestore instance to main.dart
in the Initialize Firestore step.
<code_start>final firestore = context.read<FirebaseFirestore?>();
if (firestore == null) {
_log.warning("Firestore instance wasn't provided. "
'Running without _firestoreController.');
} else {
_firestoreController = FirestoreController(
instance: firestore,
boardState: _boardState,
);
}<code_end>
Dispose of the controller using the dispose() method
of the same class.
<code_start>_firestoreController?.dispose();<code_end>
<topic_end>
<topic_start>
6. Test the game
Run the game on two separate devices
or in 2 different windows on the same device.Watch how adding a card to an area on one device
makes it appear on the other one.Open the Firebase web console
and navigate to your project’s Firestore Database.Watch how it updates the data in real time.
You can even edit the data in the console
and see all running clients update.<topic_end>
<topic_start>
Troubleshooting