Skip to content

Commit 0ff5b9c

Browse files
committed
ChangeNotifierProviderSample fix:
- Load todos when the app is first launched, not any time a listener is added - Test loading of the todos from the repository
1 parent a4665bb commit 0ff5b9c

File tree

4 files changed

+20
-9
lines changed

4 files changed

+20
-9
lines changed

change_notifier_provider/lib/app.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class ProviderApp extends StatelessWidget {
2323
@override
2424
Widget build(BuildContext context) {
2525
return ChangeNotifierProvider(
26-
create: (_) => TodoListModel(repository: repository),
26+
create: (_) => TodoListModel(repository: repository)..loadTodos(),
2727
child: MaterialApp(
2828
theme: ArchSampleTheme.theme,
2929
localizationsDelegates: [

change_notifier_provider/lib/todo_list_model.dart

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,6 @@ class TodoListModel extends ChangeNotifier {
3939
}) : _todos = todos ?? [],
4040
_filter = filter ?? VisibilityFilter.all;
4141

42-
@override
43-
void addListener(VoidCallback listener) {
44-
super.addListener(listener);
45-
// update data for every subscriber, especially for the first one
46-
loadTodos();
47-
}
48-
4942
/// Loads remote data
5043
///
5144
/// Call this initially and when the user manually refreshes

change_notifier_provider/pubspec.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ environment:
1717
sdk: ">=2.6.0 <3.0.0"
1818

1919
dependencies:
20-
provider: ^4.0.1
20+
provider: ^4.0.4
2121
todos_repository_local_storage:
2222
path: ../todos_repository_local_storage
2323
todos_app_core:

change_notifier_provider/test/app_state_test.dart renamed to change_notifier_provider/test/todo_list_model_test.dart

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,5 +141,23 @@ void main() {
141141
expect(model.todos, [todo1, update, todo3]);
142142
expect(repository.saveCount, 1);
143143
});
144+
145+
test('should load todos from the repository', () async {
146+
final todos = [Todo('a'), Todo('b'), Todo('c', complete: true)];
147+
final repository = MockRepository(todos);
148+
final model = TodoListModel(repository: repository);
149+
150+
expect(model.isLoading, isFalse);
151+
expect(model.todos, []);
152+
153+
final loading = model.loadTodos();
154+
155+
expect(model.isLoading, isTrue);
156+
157+
await loading;
158+
159+
expect(model.isLoading, isFalse);
160+
expect(model.todos, todos);
161+
});
144162
});
145163
}

0 commit comments

Comments
 (0)