Created
March 19, 2023 22:40
-
-
Save RahmiTufanoglu/f937f5e05916ec0f9f8741a5c325dec1 to your computer and use it in GitHub Desktop.
TODO Inherited Widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Todo { | |
String title; | |
bool isDone; | |
Todo({ | |
required this.title, | |
this.isDone = false, | |
}); | |
} | |
class TodoList { | |
List<Todo> todos = []; | |
void add(Todo todo) { | |
todos.add(todo); | |
} | |
void remove(Todo todo) { | |
todos.remove(todo); | |
} | |
void toggle(Todo todo) { | |
todo.isDone = !todo.isDone; | |
} | |
} | |
class TodoProvider extends InheritedWidget { | |
final TodoList todoList; | |
TodoProvider({ | |
Key? key, | |
required this.todoList, | |
required Widget child, | |
}) : super(key: key, child: child); | |
static TodoProvider of(BuildContext context) { | |
return context.dependOnInheritedWidgetOfExactType<TodoProvider>()!; | |
} | |
@override | |
bool updateShouldNotify(TodoProvider oldWidget) { | |
return todoList != oldWidget.todoList; | |
} | |
} | |
class TodoListScreen extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
final todoList = TodoProvider.of(context).todoList; | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Todo List'), | |
), | |
body: ListView.builder( | |
itemCount: todoList.todos.length, | |
itemBuilder: (context, index) { | |
final todo = todoList.todos[index]; | |
return CheckboxListTile( | |
title: Text(todo.title), | |
value: todo.isDone, | |
onChanged: (_) { | |
TodoProvider.of(context).todoList.toggle(todo); | |
}, | |
); | |
}, | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
final todo = Todo( | |
title: 'New todo', | |
); | |
TodoProvider.of(context).todoList.add(todo); | |
}, | |
child: Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment