flutter - 如何在 flutter 中按日期动态排序?

标签 flutter dart

我正在开发一个关于 flutter 的待办事项列表应用程序,我想按日期对上传的任务进行排序(新任务首先出现)。为此,我认为应该为待办事项列表中的每个上传项目提供一个 key ,并且该 key 应包含一个日期。为了做到这一点,我在一个按日期排序的平面列表中的数据中添加了一个函数,但由于我是新来的,所以我不知道该怎么做。任何想法都有帮助:)
主要.dart

  List<String> _toDoItems = []; //this is the array in which the uploaded tasks are stored, btw Im not using any database.
  TextEditingController _controller = TextEditingController();

  void _addToDoItem(String task) {
    if(task.length > 0) {
      setState(() {  
        _toDoItems.add(task);
      });
    }
  }

  void _removeTodoItem(int index) {
    setState(() => _toDoItems.removeAt(index));
  }

  Widget _buildToDoItem(String toDoText, int index) {
    return SizedBox(
      child: Container(
        height: 58,
        margin: EdgeInsets.only(left: 22.0, right: 22.0, bottom: 12,),
        decoration: BoxDecoration(
          border: Border.all(width: 1.5, color: Colors.red),
          borderRadius: BorderRadius.all(Radius.circular(18)),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children:[
            Expanded(
              child: ListTile(
                title: Text(
                  toDoText,
                  style: TextStyle(fontSize: 18),
                ),
                onTap: () => _removeTodoItem(index),
              ),
            ),
            FlatButton(
              child: Text('Delete', style: TextStyle(color: Colors.red, fontSize: 16.5),),
              onPressed: () => _removeTodoItem(index),
            ),
          ],
        ),
      ),
    );
  }
  Widget _buildToDoList() {
    return Expanded(
      child: ListView.builder(
        itemBuilder: (context, index) {
          if (index < _toDoItems.length) {
            return _buildToDoItem(_toDoItems[index], index);
          }
        },
      ),
    );
  }
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(50),
          child: AppBar(
            centerTitle: true,
            backgroundColor: Colors.red,
            title: Text('To Do List', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold,),),
          )
        ),
        backgroundColor: Colors.white,
        body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                height: 60,
                margin: EdgeInsets.all(22),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      flex: 10,
                      child: Container(
                        height: double.infinity,
                        child: TextField(
                          controller: _controller,
                          autofocus: true,
                          onSubmitted: (val) {
                            _addToDoItem(val);
                            _controller.clear();
                          },
                          style: TextStyle(fontSize: 18,),
                        ),
                      ),
                      
                    ),
                    Expanded(
                      flex: 4,    
                      child: Container(
                        height: double.infinity,
                        margin: EdgeInsets.only(left: 12),
                        child: RaisedButton(
                          textColor: Colors.white,
                          color: Colors.red,
                          child: Text('ADD', style: TextStyle(fontSize: 18)),
                          
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(Radius.circular(12)),
                          ),
                          onPressed: () {
                            _addToDoItem(_controller.text);
                            _controller.clear();
                            FocusScope.of(context).requestFocus(FocusNode());
                          },
                        ),
                      ),                                          
                    ),
                  ],
                ),
              ), 
              _buildToDoList()
            ]
          ), 
                 
        ),
    );
  }

最佳答案

您需要使用 sort() List 的方法,您还需要能够以某种方式存储创建任务的时间。
我用你发布的代码做了一个例子。使用它,您最后创建的元素将始终是列表的第一个。

import 'package:flutter/material.dart';

class ToDoElement {
  final String task;
  final DateTime timeOfCreation;

  ToDoElement(this.task, this.timeOfCreation);
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  createState() => _MyAppState();
}

class _MyAppState extends State {
  TextEditingController _controller = TextEditingController();
  List<ToDoElement> _toDoItems = [];

  void _removeTodoItem(int index) {
    setState(() => _toDoItems.removeAt(index));
  }

  void _addToDoItem(String task) {
    if (task.isNotEmpty) {
      setState(() => _toDoItems.add(ToDoElement(task, DateTime.now())));
    }
  }

  Widget _buildToDoItem(String toDoText, int index) {
    return SizedBox(
      child: Container(
        height: 58,
        margin: EdgeInsets.only(left: 22, right: 22, bottom: 12),
        decoration: BoxDecoration(
          border: Border.all(width: 1.5, color: Colors.red),
          borderRadius: BorderRadius.all(Radius.circular(18)),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
              child: ListTile(
                title: Text(
                  toDoText,
                  style: TextStyle(fontSize: 18),
                ),
                onTap: () => _removeTodoItem(index),
              ),
            ),
            FlatButton(
              child: Text(
                'Delete',
                style: TextStyle(color: Colors.red, fontSize: 16.5),
              ),
              onPressed: () => _removeTodoItem(index),
            ),
          ],
        ),
      ),
    );
  }

  int compareElement(ToDoElement a, ToDoElement b) =>
      a.timeOfCreation.isAfter(b.timeOfCreation) ? -1 : 1;

  Widget _buildToDoList() {
    _toDoItems.sort(compareElement);
    return Expanded(
      child: ListView.builder(
        itemCount: _toDoItems.length,
        itemBuilder: (context, index) {
          return _buildToDoItem(_toDoItems[index].task, index);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: PreferredSize(
            preferredSize: Size.fromHeight(50),
            child: AppBar(
              centerTitle: true,
              backgroundColor: Colors.red,
              title: Text(
                'To Do List',
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
            )),
        backgroundColor: Colors.white,
        body: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
          Container(
            height: 60,
            margin: EdgeInsets.all(22),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  flex: 10,
                  child: Container(
                    height: double.infinity,
                    child: TextField(
                      controller: _controller,
                      autofocus: true,
                      onSubmitted: (val) {
                        _addToDoItem(val);
                        _controller.clear();
                      },
                      style: TextStyle(
                        fontSize: 18,
                      ),
                    ),
                  ),
                ),
                Expanded(
                  flex: 4,
                  child: Container(
                    height: double.infinity,
                    margin: EdgeInsets.only(left: 12),
                    child: RaisedButton(
                      textColor: Colors.white,
                      color: Colors.red,
                      child: Text('ADD', style: TextStyle(fontSize: 18)),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(12)),
                      ),
                      onPressed: () {
                        _addToDoItem(_controller.text);
                        _controller.clear();
                        FocusScope.of(context).requestFocus(FocusNode());
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          _buildToDoList()
        ]),
      ),
    );
  }
}

关于flutter - 如何在 flutter 中按日期动态排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63380065/

相关文章:

android - 选项卡未显示在 flutter 中

Dart 抽象私有(private)方法

timer - 如何在 flutter 中进行倒计时?

flutter - 如何在 Dart 中取消延迟的 future ?

asynchronous - 在Flutter中将Future <int>转换为int

flutter - Flutter Bloc 依赖项的多个监听器 - 接收先前的状态

android - Flutter - 无法发出 POST 请求

dart - Dart 中的逆映射

Flutter - 有没有办法禁用 ExpansionTile 的扩展?

firebase - 不实时加载值