본문 바로가기

Flutter/10 app Todo with provider

[Flutter] App Todo(ChangeNotifierProxyProvider -> ProxyProvider)

오늘은 ChangeNotifierProxyProvider 를 ProxyProvider 로 변경해보겠습니다.

ChangeNotifierProxyProvider 를 사용하지만 내부적으로 저장할 state 가 없으면 변경가능하다.

대상은 todo_active_count.dart, filtered_todos.dart, main.dart 이다.

개발환경 : 윈도우11, 안드로이드 스튜디오, flutter 2.10.3

소스코드 위치 - 08_ProxyProvider · mike-bskim/todo_test (github.com)

 

Release 08_ProxyProvider · mike-bskim/todo_test

 

github.com

 

 

todo_active_count.dart 수정

 

class TodoActiveCount {
  final TodoList todoList;
  TodoActiveCount({required this.todoList});

  TodoActiveCountState get state => TodoActiveCountState(
        todoActiveCount: todoList.state.todos
            .where((Todo todo) => !todo.completed)
            .toList()
            .length,
      );
}

 

filtered_todos.dart 수정

 

class FilteredTodos {
  final TodoList todoList;
  final TodoFilter todoFilter;
  final TodoSearch todoSearch;
  FilteredTodos({
    required this.todoList,
    required this.todoFilter,
    required this.todoSearch,
  });

  FilteredTodosState get state {
    List<Todo> _filteredTodos;

    switch (todoFilter.state.filter) {
      case Filter.active:
        _filteredTodos =
            todoList.state.todos.where((Todo todo) => !todo.completed).toList();
        break;
      case Filter.completed:
        _filteredTodos =
            todoList.state.todos.where((Todo todo) => todo.completed).toList();
        break;
      case Filter.all:
      default:
        _filteredTodos = todoList.state.todos;
        break;
    }

    if (todoSearch.state.searchTerm.isNotEmpty) {
      _filteredTodos = _filteredTodos
          .where((Todo todo) =>
              todo.desc.toLowerCase().contains(todoSearch.state.searchTerm))
          .toList();
    }

    return FilteredTodosState(filteredTodos: _filteredTodos);
  }
}

 

main.dart 수정

 

providers: [
  ChangeNotifierProvider<TodoList>(create: (context) => TodoList()),
  ChangeNotifierProvider<TodoFilter>(create: (context) => TodoFilter()),
  ChangeNotifierProvider<TodoSearch>(create: (context) => TodoSearch()),
  ProxyProvider3<TodoFilter, TodoSearch, TodoList, FilteredTodos>(
    // 생성시 TodoList 를 확인해서 초기화하지 않아도 update 시 처리됨.
    update: (
      BuildContext context,
      TodoFilter todoFilter,
      TodoSearch todoSearch,
      TodoList todoList,
      FilteredTodos? _,
    ) =>
        FilteredTodos(
      todoList: todoList,
      todoFilter: todoFilter,
      todoSearch: todoSearch,
    ),
  ),
  ProxyProvider<TodoList, TodoActiveCount>(
    // 생성시 TodoList 를 확인해서 초기화하지 않아도 update 시 처리됨.
    update: (
      BuildContext context,
      TodoList todoList,
      TodoActiveCount? _,
    ) =>
        TodoActiveCount(todoList: todoList),
  )
],

 

 

 

 

[참고자료] udemy - Flutter Provider Essential 코스 (Korean)