我有一个通知页面有三个类别; New、This Week和Oldest。New中的通知是当天收到的通知,This week中的通知是七天内收到的通知。而Oldest都是一周以上的。收到通知的时间也附在通知之后。我该如何实现这一点?
New
This Week
Oldest
This week
7ivaypg91#
完全正确,正如jamesdlin所说,你需要一个名单。如果你分享你的代码,这将很容易。下面是一个例子
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class NotificationItem { String title; DateTime time; NotificationItem({required this.title, required this.time}); } class NotificationsPage extends StatefulWidget { const NotificationsPage({Key? key}) : super(key: key); @override _NotificationsPageState createState() => _NotificationsPageState(); } class _NotificationsPageState extends State<NotificationsPage> { List<NotificationItem> _notifications = [ NotificationItem( title: 'New notification 1', time: DateTime.now().subtract(Duration(hours: 1))), NotificationItem( title: 'New notification 2', time: DateTime.now().subtract(Duration(minutes: 30))), NotificationItem( title: 'This week notification 1', time: DateTime.now().subtract(Duration(days: 3))), NotificationItem( title: 'This week notification 2', time: DateTime.now().subtract(Duration(days: 6))), NotificationItem( title: 'Old notification 1', time: DateTime.now().subtract(Duration(days: 10))), NotificationItem( title: 'Old notification 2', time: DateTime.now().subtract(Duration(days: 14))), ]; List<NotificationItem> get _newNotifications { return _notifications.where((notification) => notification.time.isAfter(DateTime.now().subtract(Duration(days: 1)))).toList(); } List<NotificationItem> get _thisWeekNotifications { return _notifications.where((notification) => notification.time.isAfter(DateTime.now().subtract(Duration(days: 7))) && notification.time.isBefore(DateTime.now().subtract(Duration(days: 1)))).toList(); } List<NotificationItem> get _oldestNotifications { return _notifications.where((notification) => notification.time.isBefore(DateTime.now().subtract(Duration(days: 7)))).toList(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Notifications'), ), body: Column( children: [ _buildCategory('New', _newNotifications), _buildCategory('This Week', _thisWeekNotifications), _buildCategory('Oldest', _oldestNotifications), ], ), ); } Widget _buildCategory(String title, List<NotificationItem> notifications) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text(title, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), ), Divider(), ListView.builder( shrinkWrap: true, physics: ClampingScrollPhysics(), itemCount: notifications.length, itemBuilder: (context, index) { return ListTile( title: Text(notifications[index].title), subtitle: Text(DateFormat('EEE, MMM d, yyyy - h:mm a').format(notifications[index].time)), ); }, ), ], ); } }
1条答案
按热度按时间7ivaypg91#
完全正确,正如jamesdlin所说,你需要一个名单。如果你分享你的代码,这将很容易。下面是一个例子