【问题标题】:How can I update a filtered list in Flutter?如何更新 Flutter 中的过滤列表?
【发布时间】:2022-01-05 17:19:24
【问题描述】:

我正在用 Flutter 开发一个待办事项应用程序。

我目前正在尝试删除所有已完成的待办事项,但不知何故我无法更新主列表中已完成的部分。我正在使用 Provider 作为状态管理。

  • 我想做什么:当我点击清除待办事项按钮时,删除我的待办事项列表中所有已完成的待办事项。我不想删除所有待办事项。我只想清除所有“已完成”的待办事项。

TodosProvider 代码

import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todo_app/Models/todo.dart';

class TodosProvider extends ChangeNotifier {
  SharedPreferences? sharedPreferences;

  //initial state
  List<Todo> todos = [];

  //  getter
  UnmodifiableListView<Todo> get allTodos =>
      UnmodifiableListView(todos.reversed);

  UnmodifiableListView<Todo> get completedTodos =>
      UnmodifiableListView(todos.reversed.where((todo) => todo.complete));

  UnmodifiableListView<Todo> get unCompletedTodos =>
      UnmodifiableListView(todos.reversed.where((todo) => !todo.complete));

//  methods for Todo
  void addTodo(Todo todo) {
    todos.add(todo);
    saveDataToLocalStorage();
    notifyListeners();
  }

  void removeTodo(Todo todo) {
    todos.remove(todo);
    updateDataToLocalStorage();
    checkCompletedTodos();
    notifyListeners();
  }

  bool checkCompletedTodos() {
    if (completedTodos.isEmpty) {
      notifyListeners();
      return true;
    }
    notifyListeners();
    return false;
  }

  void removeCompletedTodos() {
    List<Todo> compTodos = (todos.where((todo) => todo.complete).toList());
    print('length before delete : ${compTodos.length}');
    compTodos.clear();
    todos.where((todo) => todo.complete) == compTodos;
    print('length after clear: ${compTodos.length}');
    todos.addAll(compTodos);
    updateDataToLocalStorage();
    print('List deleted');
    notifyListeners();

  }

  void toggleTodo(Todo todo) {
    var index = todos.indexOf(todo);
    todos[index].toggleCompleted();
    updateDataToLocalStorage();
    notifyListeners();
  }

  // methods for shared preferences
  void initSharedPreferences() async {
    sharedPreferences = await SharedPreferences.getInstance();
    loadDataFromLocalStorage();
    notifyListeners();
  }

  // Percent Method
  double calcTodoPercent() {
    double percent = (completedTodos.length / allTodos.length);
    print('Percent : $percent');
    print('Comp todos : ${completedTodos.length}');
    print('UnComp todos : ${unCompletedTodos.length}');
    print(percent.runtimeType);
    return (completedTodos == 0 && unCompletedTodos == 0) ? 0 : percent;
  }

  void saveDataToLocalStorage() {
    List<String>? spList =
        todos.map((todo) => json.encode(todo.toJson())).toList();
    sharedPreferences!.setStringList('list', spList);
  }

  void loadDataFromLocalStorage() {
    List<String>? spList = sharedPreferences!.getStringList('list');
    todos = spList!.map((item) => Todo.fromMap(json.decode(item))).toList();
  }

  void updateDataToLocalStorage() {
    List<String>? spList =
        todos.map((item) => json.encode(item.toJson())).toList();
    sharedPreferences?.remove('list');
    sharedPreferences!.setStringList('list', spList);
  }
}

仪表板页面按钮代码:

import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:todo_app/Widgets/Dashboard/complete_todo_list.dart';
import 'package:todo_app/Widgets/Dashboard/completed_task_info.dart';

class DashboardPage extends StatefulWidget {
  const DashboardPage({Key? key}) : super(key: key);

  @override
  _DashboardPageState createState() => _DashboardPageState();
}

class _DashboardPageState extends State<DashboardPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DashboardAP(),
      body: Container(
        color: HexColor('#f9f6e8'),
        child: Column(
          children: const [
            CompletedTaskInfo(),
            CompleteTodoList()
          ],
        ),
      ),
    );
  }
}

AppBar DashboardAP() {
  return AppBar(
    leading: const Padding(
        padding: EdgeInsets.only(left: 10.0, top: 15.0),
        child: Icon(Icons.settings, color: Colors.black)),
    //Icon(Icons.settings),
    backgroundColor: HexColor('#f9f6e8'),
    elevation: 0,
  );
}

completed_task_ifo 小部件代码:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:todo_app/provider/todos_provider.dart';

class CompletedTaskInfo extends StatefulWidget {
  const CompletedTaskInfo({Key? key}) : super(key: key);

  @override
  _Task_InfoState createState() => _Task_InfoState();
}

class _Task_InfoState extends State<CompletedTaskInfo> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 10.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Your tasks',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
                Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Consumer<TodosProvider>(
                      builder: (context, state, child) => Text(
                        'You have ${state.completedTodos.length} tasks completed all time',
                        style: const TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            color: Colors.grey),
                      ),
                    ))
              ],
            ),
          ),
          ElevatedButton(onPressed:
          () {
            Provider.of<TodosProvider>(context,listen: false).checkCompletedTodos() ? print('Şuan da liste boş')
                : Provider.of<TodosProvider>(context,listen: false).removeCompletedTodos();
          }

            , child: const Text('Clear Todos',style: TextStyle(fontSize: 10),),
            style: ElevatedButton.styleFrom(shape: StadiumBorder()),
          )
        ],
      ),
    );
  }
}

已完成的待办事项列表小部件代码:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:todo_app/Models/todo.dart';
import 'package:todo_app/Pages/detail_screen.dart';
import 'package:todo_app/Widgets/Todo/todo_card.dart';
import 'package:todo_app/provider/todos_provider.dart';

import 'complete_todo_card.dart';

class CompleteTodoList extends StatefulWidget {
  const CompleteTodoList({Key? key}) : super(key: key);

  @override
  _CompleteTodoListState createState() => _CompleteTodoListState();
}

class _CompleteTodoListState extends State<CompleteTodoList> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 20.0),
      child: Consumer<TodosProvider>(
        builder: (context, state, child) => SizedBox(
          height: MediaQuery.of(context).size.height / 1.48,
          child: ListView.builder(
              itemCount: state.completedTodos.length,
              itemBuilder: (context, index) {
                return CompleteTodoCard(
                  todo: state.completedTodos[index],
                );
              }),
        ),
      ),
    );
  }
}

从技术上讲,我这样做了,但没有任何变化,因为我无法更新我的主列表。

我整天都在研究这个问题,但找不到任何东西并解决它。如果您能提供帮助,我将非常高兴。

【问题讨论】:

  • 您遇到错误了吗?
  • 不,我没有在代码中发现任何错误。我无法直接更新我的主列表。删除工作正常,但没有更新我的主要待办事项列表。 @fartem

标签: list flutter dart


【解决方案1】:

没有人回答,但我刚刚解决了。我可以使用以下方法删除列表中已完成的待办事项。

  void removeCompletedTodos() {
    todos.forEach((todo) {
      if (todo.complete) {
        var index = todos.indexOf(todo);
        completedTodosList.add(todo);
        notifyListeners();
      }
    });
    todos.removeWhere((todo) => completedTodosList.contains(todo));
    updateDataToLocalStorage();
    notifyListeners();
  }

我的其他代码都是一样的,我只是创建了一个新列表来标记完成。

List<Todo> completedTodosList = [];

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    相关资源
    最近更新 更多