我正在试用一个flutter应用程序,该应用程序可以计算两个日期之间的时差并以天为单位显示。
但是由于某种原因,我无法理解正确的逻辑。我创建了足够的变量来保存当前日期,并创建了另一个变量来保存旧日期,但是仍然缺少一些东西。
我使用了FLutter_datetime_picker软件包。
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.dark(),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final currentDate = DateTime.now();
final oldDate = DateTime.tryParse();
final difference = currentDate.difference(oldDate).inDays;
return Scaffold(
body: Row(
children: <Widget>[
Center(
child: RaisedButton(
child: Text("data"),
onPressed: () => DatePicker.showDatePicker(context,
showTitleActions: true,
currentTime: currentDate,
minTime: DateTime(1990, 1, 1), onConfirm: (date) {
setState(() {
date = oldDate;
});
print(difference);
})),
),
Text(difference.toString())
],
),
);
}
}
答案 0 :(得分:1)
您应该将变量放在build()
方法之外,因为在调用setState()
时会再次调用build()
方法。
您可以在initState()
方法中初始化变量,或者在这种情况下,您可以通过初始化来声明它们。
答案 1 :(得分:1)
在onConfirm
方法中选择新日期时,您可以计算出这种差异:
class _MyHomePageState extends State<MyHomePage> {
DateTime currentDate = DateTime.now();
String difference = "";
@override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: <Widget>[
Center(
child: RaisedButton(
child: Text("data"),
onPressed: () => DatePicker.showDatePicker(
context,
showTitleActions: true,
currentTime: currentDate,
minTime: DateTime(1990, 1, 1),
onConfirm: (date) {
setState(() {
difference = "${currentDate.difference(date).inDays}";
});
print(difference);
},
),
),
),
Text(difference),
],
),
);
}
}