...

/

Solution: State Management

Solution: State Management

Explore solutions to the Riverpod challenges.

We'll cover the following...

Solutions

Follow the steps below and compare your answers to each challenge you attempted in the previous lesson.

Challenge 1: Add Packages

We go to line 16 of the pubspec.yaml file and replace # TODO-1: Add flutter_riverpod package with the line below:

flutter_riverpod: ^1.0.0

Challenge 2: Complete the TasksChangeNotifier class

import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/task.dart';
final tasksProvider = ChangeNotifierProvider<TasksChangeNotifier>((ref) => TasksChangeNotifier());
class TasksChangeNotifier extends ChangeNotifier {
final List<Task> _tasks = [];
UnmodifiableListView<Task> get tasks {
return UnmodifiableListView(_tasks);
}
int get tasksLength => _tasks.length;
void addTask(String task) {
_tasks.add(Task(name: task));
notifyListeners();
}
void deleteTask(index) {
_tasks.removeAt(index);
notifyListeners();
}
void toggleDone(index) {
_tasks[index].isDone = !_tasks[index].isDone;
notifyListeners();
}
}
  1. We first import the flutter_riverpod package (line 4).

  2. On line 7, we declare a tasksProvider object, which creates and exposes an instance of TasksChangeNotifier to be accessed elsewhere within the application.

  3. Line 19 allows us to add a single task to the list of tasks given its string name. Note that after adding a new task to the list, we call the notifyListeners() method (line 20), which notifies the users of the TasksChangeNotifier object that the object changes.

  4. On line 24, we delete the task occupying the provided index and then ...