Skip to content

Instantly share code, notes, and snippets.

@RahmiTufanoglu
Created March 19, 2023 22:40
Show Gist options
  • Save RahmiTufanoglu/f937f5e05916ec0f9f8741a5c325dec1 to your computer and use it in GitHub Desktop.
Save RahmiTufanoglu/f937f5e05916ec0f9f8741a5c325dec1 to your computer and use it in GitHub Desktop.
TODO Inherited Widget
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