Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 73 ยท Projects

Project: Todo App with Persistence

Build a Flutter todo app step by step: a model, a repository with local storage, a ChangeNotifier, a list UI and tests, with live logic stand-ins.

A todo list is a classic first project because it touches every layer of a real app: a data model, a screen with a list, user input, state that changes, and saving to disk so the tasks are still there tomorrow. In this project you build it the way a larger app would be organized, so the same structure grows into anything bigger.

The pieces come from earlier lessons: model classes and JSON, ChangeNotifier, Provider, local storage and testing. Here they are assembled.

Real vs stand-in. The Dart and Flutter code is real and read-only, because the site cannot run Flutter. The live examples are JavaScript stand-ins that run the same logic: the model, the store with a fake storage, and a small test harness. The logic ports to Dart almost line by line.

The app in four layers

Model A Todo with id, title, done.
Repository Loads and saves JSON.
Controller A ChangeNotifier with the list.
UI List, add field, checkboxes.
1 / 2

Step 1: setup and the model

Create the project and add two packages:

Terminal
flutter create todo_app
cd todo_app
flutter pub add provider shared_preferences

The model is a small immutable class. copyWith makes "changing" a todo create a new one, which keeps state predictable:

DART
class Todo {
  const Todo({required this.id, required this.title, this.done = false});

  final String id;
  final String title;
  final bool done;

  Todo copyWith({String? title, bool? done}) =>
      Todo(id: id, title: title ?? this.title, done: done ?? this.done);

  Map<String, dynamic> toJson() => {'id': id, 'title': title, 'done': done};

  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
        id: json['id'] as String,
        title: json['title'] as String,
        done: json['done'] as bool? ?? false,
      );
}

Note the as bool? ?? false: if you add a field in a later version, old saved data without it still loads.

Step 2: the repository and local storage

The repository hides where data lives. The controller will never mention SharedPreferences:

DART
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

abstract class TodoRepository {
  Future<List<Todo>> load();
  Future<void> save(List<Todo> todos);
}

class PrefsTodoRepository implements TodoRepository {
  PrefsTodoRepository(this._prefs);
  final SharedPreferences _prefs;
  static const _key = 'todos_v1';

  @override
  Future<List<Todo>> load() async {
    final raw = _prefs.getString(_key);
    if (raw == null) return [];
    final list = jsonDecode(raw) as List<dynamic>;
    return [for (final item in list) Todo.fromJson(item as Map<String, dynamic>)];
  }

  @override
  Future<void> save(List<Todo> todos) =>
      _prefs.setString(_key, jsonEncode([for (final t in todos) t.toJson()]));
}

A key name with a version (todos_v1) leaves room for a migration later. For thousands of items or queries you would switch to SQLite, and only this one class would change.

Step 3: the controller

The controller owns the list, saves after every change and tells the UI to rebuild:

DART
import 'package:flutter/foundation.dart';

class TodoController extends ChangeNotifier {
  TodoController(this._repository);
  final TodoRepository _repository;

  List<Todo> _todos = [];
  bool _loaded = false;

  List<Todo> get todos => List.unmodifiable(_todos);
  bool get loaded => _loaded;
  int get remaining => _todos.where((t) => !t.done).length;

  Future<void> load() async {
    _todos = await _repository.load();
    _loaded = true;
    notifyListeners();
  }

  Future<void> add(String title) async {
    final clean = title.trim();
    if (clean.isEmpty) return;
    _todos = [..._todos, Todo(id: DateTime.now().microsecondsSinceEpoch.toString(), title: clean)];
    await _commit();
  }

  Future<void> toggle(String id) async {
    _todos = [for (final t in _todos) t.id == id ? t.copyWith(done: !t.done) : t];
    await _commit();
  }

  Future<void> remove(String id) async {
    _todos = _todos.where((t) => t.id != id).toList();
    await _commit();
  }

  Future<void> _commit() async {
    notifyListeners();                 // update the screen first
    await _repository.save(_todos);    // then persist
  }
}

Two good habits show up here: the getter returns an unmodifiable view so the UI cannot change the list behind the controller's back, and blank titles are rejected in one place instead of in every widget.

Step 4: the UI

main loads the saved list before showing the app and provides the controller to the tree:

DART
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final prefs = await SharedPreferences.getInstance();
  final controller = TodoController(PrefsTodoRepository(prefs));
  await controller.load();
  runApp(ChangeNotifierProvider.value(value: controller, child: const TodoApp()));
}

The screen watches the controller; the add field uses a local TextEditingController:

DART
class TodoScreen extends StatefulWidget {
  const TodoScreen({super.key});
  @override
  State<TodoScreen> createState() => _TodoScreenState();
}

class _TodoScreenState extends State<TodoScreen> {
  final _input = TextEditingController();

  @override
  void dispose() {
    _input.dispose();
    super.dispose();
  }

  void _submit() {
    context.read<TodoController>().add(_input.text);
    _input.clear();
  }

  @override
  Widget build(BuildContext context) {
    final controller = context.watch<TodoController>();
    return Scaffold(
      appBar: AppBar(title: Text('Todos (${controller.remaining} left)')),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(12),
            child: TextField(
              controller: _input,
              decoration: InputDecoration(
                labelText: 'New task',
                suffixIcon: IconButton(icon: const Icon(Icons.add), onPressed: _submit),
              ),
              onSubmitted: (_) => _submit(),
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: controller.todos.length,
              itemBuilder: (context, index) {
                final todo = controller.todos[index];
                return Dismissible(
                  key: ValueKey(todo.id),
                  onDismissed: (_) => controller.remove(todo.id),
                  child: CheckboxListTile(
                    value: todo.done,
                    title: Text(todo.title),
                    onChanged: (_) => controller.toggle(todo.id),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

The ValueKey(todo.id) on each Dismissible matters: without it, swiping items out of a list can leave the wrong rows on screen (see Keys and Widget Identity).

Stand-in: the store with persistence

This JavaScript version has the same shape: a fake storage that only holds strings (like SharedPreferences), a repository, and a controller. A second controller loads what the first one saved, which is what an app restart does.

JS Todos that survive a restart

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 5: tests

Because the controller depends on the abstract TodoRepository, a test can use a fake that stores the list in memory:

DART
class MemoryRepository implements TodoRepository {
  List<Todo> saved = [];
  @override
  Future<List<Todo>> load() async => saved;
  @override
  Future<void> save(List<Todo> todos) async => saved = todos;
}

void main() {
  test('add ignores blank titles', () async {
    final controller = TodoController(MemoryRepository());
    await controller.add('   ');
    expect(controller.todos, isEmpty);
  });

  test('toggle flips done and persists', () async {
    final repo = MemoryRepository();
    final controller = TodoController(repo);
    await controller.add('Milk');
    await controller.toggle(controller.todos.first.id);
    expect(repo.saved.first.done, isTrue);
  });
}

Stand-in: a mini test harness

JS Testing the controller with a fake repository

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ideas to extend it

  • Edit a todo's title with a dialog.
  • Filter tabs: All, Active, Done.
  • A due date and a sort order.
  • Replace shared_preferences with SQLite (only the repository changes).
  • A widget test that types a task, taps add and finds the new row.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the controller depend on an abstract TodoRepository?

    The controller never knows how data is stored, so you can change the storage or fake it in tests.
  2. 2. Why return List.unmodifiable(_todos) from the getter?

    All changes go through methods that save and notify listeners.
  3. 3. What does ValueKey(todo.id) on each Dismissible do?

    Stable keys let Flutter match rows to the right items when some are removed.
  4. 4. Which call reads the controller in the screen and rebuilds when it changes?

    watch subscribes the widget to the notifier; read gets it once without listening.

Summary

  • Organize even a small app in layers: model, repository, controller, UI.
  • Keep the model immutable and tolerant when loading old JSON.
  • Save after every change; the repository hides where data lives.
  • ChangeNotifier plus Provider rebuilds only the widgets that watch it.
  • Depending on an abstraction makes testing with a fake simple.

Next: Project: Weather App