如何过滤getx中的列表项

How to filter list item in getx

我有一个 to-do 应用程序,其中有一个项目列表,其中包含计划的日期和时间、标题、详细信息以及完成与否的任务。我想根据是否完成来过滤待办事项列表,如何在 getx 控制器中实现它。

型号:

class Todo {
  String title;
  String details;
  String? date;
  String? time;
  bool done;
  bool dateAndTimeEnabled;
  int id;
  Todo(
      {required this.title,
      required this.details,
      required this.date,
      required this.time,
      this.dateAndTimeEnabled = true,
      required this.id,
      this.done = false});

  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
      id: json['id'],
      title: json['title'],
      details: json['details'],
      done: json['done'],
      date: json['date'],
      time: json['time'],
      dateAndTimeEnabled: json['dateAndTimeEnabled']);

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

Getx 控制器:

class TodoController extends GetxController {
  var todos = <Todo>[].obs;

  @override
  void onInit() {
List? storedTodos = GetStorage().read<List>('todos');

if (storedTodos != null) {
  todos.assignAll(storedTodos.map((e) => Todo.fromJson(e)).toList());
}
ever(todos, (_) {
  GetStorage().write('todos', todos.toList());
});
super.onInit();
  }
}

更新

@override
  void initState() {
   todoController.getDoneTodos();
  super.initState();
 }


GestureDetector(
        onTap: () {
          Get.to(() => const doneTodos());
        },
        child: Padding(
          padding: const EdgeInsets.only(top: 20.0, left: 14.0, right: 12.0),
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
              Text('${todoController.doneTodos.length}', style: Theme.of(context).textTheme.headline1,),
              Text("Done", style: Theme.of(context).textTheme.headline1)
            ],),
            padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0),
            height: 138.0,
            width: double.infinity,
             decoration: BoxDecoration(
                  color: Theme.of(context).canvasColor,
                  boxShadow: [
                      BoxShadow(
                          color: Theme.of(context).shadowColor,
                          offset: const Offset(2.5, 2.5),
                          blurRadius: 5.0,
                          spreadRadius: 1.0,
                      ), 
                  ],
                borderRadius:
                BorderRadius.circular(14.0))
          ),
        ),
      ),

我尝试用 Obx 包装文本小部件,但它抛出此错误:FlutterError(在构建过程中调用了 setState() 或 markNeedsBuild()。

在您的控制器中:

var doneTodos = <Todo>[].obs;



getDoneTodos(){
   doneTodo.assignAll(todos.where(element)=>element.done == true).toList());
}