Skip to content

Commit

Permalink
Updated widgets to listen to ChangeNotifier events
Browse files Browse the repository at this point in the history
  • Loading branch information
craiglabenz committed Oct 15, 2020
1 parent 3bf17b9 commit dfb584f
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
19 changes: 15 additions & 4 deletions lib/counter_manager.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebasecounter/app_state.dart';
import 'package:flutter/material.dart';

/// Interface that defines the functions required to manipulate
/// the app state.
///
/// Defined as an abstract class so that tests can operate on a
/// version that does not communicate with Firebase.
abstract class ICounterManager {
abstract class ICounterManager extends ChangeNotifier {
/// Any `CounterManager` must have an instance of the state
/// object.
AppState state;
Expand All @@ -17,12 +18,21 @@ abstract class ICounterManager {
void increment();
}

class CounterManager implements ICounterManager {
class CounterManager extends ChangeNotifier implements ICounterManager {
AppState state = AppState();
void increment() => state = state.copyWith(DateTime.now());

/// Copies the state object with the timestamp of the most
/// recent click and tells the stream to update.
void increment() {
state = state.copyWith(DateTime.now());
// Adding this line is how `ChangeNotifier` tells widgets to
// re-render themselves.
notifyListeners();
}
}

class FirestoreCounterManager implements ICounterManager {
class FirestoreCounterManager extends ChangeNotifier
implements ICounterManager {
AppState state;
final FirebaseFirestore _firestore;
FirestoreCounterManager()
Expand Down Expand Up @@ -51,6 +61,7 @@ class FirestoreCounterManager implements ICounterManager {
.toList();
// Part 7
state = AppState(_clicks);
notifyListeners();
});
}

Expand Down
2 changes: 1 addition & 1 deletion lib/dependencies.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class DependenciesProvider extends StatelessWidget {
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<ICounterManager>(
ChangeNotifierProvider<ICounterManager>(
create: (context) => FirestoreCounterManager()),
],
child: child,
Expand Down
2 changes: 1 addition & 1 deletion lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class _MyHomePageState extends State<MyHomePage> {
),
floatingActionButton: FloatingActionButton(
// Reference `widget.manager` instead of `manager` directly
onPressed: () => setState(() => widget.manager.increment()),
onPressed: () => widget.manager.increment(),
tooltip: 'Increment',
child: Icon(Icons.add),
),
Expand Down

0 comments on commit dfb584f

Please sign in to comment.