import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// 定义Todo模型
class Todo {
final String title;
final bool completed;
Todo(this.title, this.completed);
}
// 定义Todo模型的StateNotifier,用于管理Todo列表状态
class TodosNotifier extends StateNotifier<List<Todo>> {
TodosNotifier() : super([]);
void addTodo(String title) {
state = [...state, Todo(title, false)];
}
void removeTodo(Todo todo) {
state = state.where((element) => element != todo).toList();
}
void toggleTodo(Todo todo) {
state = state.map((t) {
if (t == todo) {
return Todo(t.title, !t.completed);
}
return t;
}).toList();
}
}
// 使用StateNotifierProvider来提供TodosNotifier的实例
final todosProvider = StateNotifierProvider<TodosNotifier, List<Todo>>((ref) {
return TodosNotifier();
});
// 创建TodoList视图
class TodoList extends ConsumerWidget {
const TodoList({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
final todo = todos[index];
return CheckboxListTile(
title: Text(todo.title),
value: todo.completed,
onChanged: (value) {
ref.read(todosProvider.notifier).toggleTodo(todo);
},
);
},
);
}
}
void main() {
runApp(const ProviderScope(child: TodoApp()));
}
class TodoApp extends StatelessWidget {
const TodoApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Padding(
padding: EdgeInsets.all(16.0),
child: TodoList(),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const AddTodoScreen(),
));
},
child: const Icon(Icons.add),
),
),
);
}
}
class AddTodoScreen extends ConsumerStatefulWidget {
const AddTodoScreen({Key? key}) : super(key: key);
@override
_
评论已关闭