如何通过DateTime筛选listview



我正在尝试创建一个传感器读数监测应用程序,我需要得到读数的记录。我已经按照数据库发送的时间顺序在列表视图中编写了记录。我需要能够搜索的日期,并得到所有的读数,是沿着这一天收到。这是我的数据来源:http://mushroomdroid.online/dbscript - 1. - php

,下面是我使用listview显示数据的方式:

class RecordsPage extends StatefulWidget {
const RecordsPage({Key key}) : super(key: key);
@override
State<RecordsPage> createState() => _RecordsPageState();
}

class _RecordsPageState extends State<RecordsPage> {
final String url = "http://mushroomdroid.online/dbscript-1.php";
List<Readings> AllData = [];
final controller = TextEditingController();
@override
void initState() {
loadData();
}
loadData() async {
var response =
await http.get(Uri.parse(url), headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
String responseBody = response.body;
var jsonBody = json.decode(responseBody);
for (var data in jsonBody) {
AllData.add(new Readings(
int.parse(data['id']),
double.parse(data['temperature']),
double.parse(data['humidity']),
data['FanStatus'],
data['MistStatus'],
DateTime.parse(data['Time'])));
}
setState(() {});
AllData.forEach((someData) => print("FanStatus: ${someData.FanStatus}"));
} else {
print('Something went wrong');
}
}
@override
Widget build(BuildContext context) {
var container;
return ListView.builder(
itemCount: AllData.length,
itemBuilder: (_, index) {
return new Container(
child: new Card(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/records.jpg'),
fit: BoxFit.fill,
)),
padding: new EdgeInsets.all(12.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(
'READINGS ON: ${AllData[index].Time}',
style: TextStyle(fontSize: 10),
),
new Text(
'TEMPERATURE: ${AllData[index].temperature}',
style: TextStyle(fontSize: 20),
),
new Text(
'HUMIDITY: ${AllData[index].humidity}',
style: TextStyle(fontSize: 20),
),
new Text(
'FAN STATUS: ${AllData[index].FanStatus}',
style: TextStyle(fontSize: 15),
),
new Text(
'MIST STATUS: ${AllData[index].FanStatus}',
style: TextStyle(fontSize: 15),
),
],
),
),
),
);
});
}
}

请帮帮我。提前感谢!

loadData()方法for (var data in jsonBody)中,您可以在执行AllData.add之前添加一些条件来检查datetime是否有效。

:我写了一个过滤器扩展,允许我根据我的条件(按名称或时间过滤)获得新的列表。

import 'package:intl/intl.dart';
final timeFm = DateFormat.yMd();
void main() {
var history = <LogHistory>[
LogHistory("A", DateTime(1990, 1, 1).millisecondsSinceEpoch),
LogHistory("A", DateTime(2020, 1, 1).millisecondsSinceEpoch),
LogHistory("B", DateTime(2020, 1, 1).millisecondsSinceEpoch),
];

print('originalObjects: $history');
print('---------------------------------------');
print('filtered by name: A');
print('result: ${history.filterBy(name: "A")}');

print('---------------------------------------');
print('filtered by time: 1/1/2000');
print('result: ${history.filterBy(time: DateTime(2000, 1, 1).millisecondsSinceEpoch)}');

print('---------------------------------------');
print('filtered by time: 1/1/2020');
print('result: ${history.filterBy(time: DateTime(2020, 1, 1).millisecondsSinceEpoch)}');

print('---------------------------------------');
print('filtered by both name & time: B + 1/1/2020');
print('result: ${history.filterBy(name: "B", time: DateTime(2020, 1, 1).millisecondsSinceEpoch)}');
}
class LogHistory {
String name;
int timeInMiliseconds;
LogHistory(this.name, this.timeInMiliseconds);

DateTime get time => DateTime.fromMillisecondsSinceEpoch(timeInMiliseconds);

@override
String toString() => "{name: $name, time: ${timeFm.format(time)}}";
}
extension LFilter on List<LogHistory> {
List<LogHistory> filterBy({String? name, int? time}){
final nameFilter = name ?? "";
final timeFilter = time != null ? DateTime.fromMillisecondsSinceEpoch(time) : null;
List<LogHistory> ret = [];
for (var object in this) {
var passFilter = true;
if(nameFilter.isNotEmpty && object.name != nameFilter){
passFilter = false;
}
if(timeFilter != null && object.time != timeFilter){
passFilter = false;
}
if(passFilter) ret.add(object);
}
return ret;
}
}

结果:

originalObjects: [{name: A, time: 1/1/1990}, {name: A, time: 1/1/2020}, {name: B, time: 1/1/2020}]
---------------------------------------
filtered by name: A
result: [{name: A, time: 1/1/1990}, {name: A, time: 1/1/2020}]
---------------------------------------
filtered by time: 1/1/2000
result: []
---------------------------------------
filtered by time: 1/1/2020
result: [{name: A, time: 1/1/2020}, {name: B, time: 1/1/2020}]
---------------------------------------
filtered by both name & time: B + 1/1/2020
result: [{name: B, time: 1/1/2020}]

:使用json更新示例

import 'package:intl/intl.dart';
final timeFm = DateFormat.yMd();
final json = [
{
"id": "1416",
"temperature": "32.65",
"humidity": "379.4",
"FanStatus": "ON",
"MistStatus": "OFF",
"Time": "2022-05-11 04:30:55"
},
{
"id": "1415",
"temperature": "32.47",
"humidity": "70.61",
"FanStatus": "ON",
"MistStatus": "ON rn",
"Time": "2022-05-11 04:20:54"
},
{
"id": "1352",
"temperature": "29.02",
"humidity": "77.61",
"FanStatus": "ON",
"MistStatus": "ON rn",
"Time": "2022-05-10 16:48:57"
},
{
"id": "1351",
"temperature": "28.99",
"humidity": "383.65",
"FanStatus": "OFF",
"MistStatus": "OFF",
"Time": "2022-05-10 16:38:57"
},
{
"id": "34",
"temperature": "33.71",
"humidity": "68.53",
"FanStatus": "ON",
"MistStatus": "ON",
"Time": "2021-06-01 03:31:47"
},
{
"id": "33",
"temperature": "33.7",
"humidity": "68.61",
"FanStatus": "ON",
"MistStatus": "ON",
"Time": "2021-05-09 03:31:47"
},
];
void main() {
var history = json.map(LogHistory.fromJson).toList();
print('total results from api: ${history.length}');
print('---------------------------------------');
print('filter by year: 2021');
print('found: ${history.filterByTime(year: 2021).length}');
print('---------------------------------------');
print('filter by month: 5');
print('found: ${history.filterByTime(month: 5).length}');
print('---------------------------------------');
print('filter by day: 10');
print('found: ${history.filterByTime(day: 10).length}');

print('---------------------------------------');
print('filter by both year and month: 2021-06');
print('found: ${history.filterByTime(year: 2021, month: 6).length}');
}
class LogHistory {
int id;
String timeRaw;
LogHistory.fromJson(Map<String, dynamic> data)
: id = int.parse(data['id']),
timeRaw = data['Time'];
DateTime get time => DateTime.parse(timeRaw);
@override
String toString() => "{id: $id, time: ${timeFm.format(time)}}";
}
extension LFilter on List<LogHistory> {
List<LogHistory> filterByTime({int? year, int? month, int? day}) {
List<LogHistory> ret = [];
for (var object in this) {
var passFilter = true;
if (year != null && object.time.year != year) {
passFilter = false;
}
if (month != null && object.time.month != month) {
passFilter = false;
}
if (day != null && object.time.day != day) {
passFilter = false;
}
if (passFilter) ret.add(object);
}
return ret;
}
}

结果:

total results from api: 6
---------------------------------------
filter by year: 2021
found: 2
---------------------------------------
filter by month: 5
found: 5
---------------------------------------
filter by day: 10
found: 2
---------------------------------------
filter by both year and month: 2021-06
found: 1

最新更新