Reputation: 1082
I am trying out a flutter application which can calculate the difference between two dates and display it in days.
But for some reason, I couldn't get the logic correct. I created enough variables to hold the current date and another variable to hold the old date, But still, I'm missing something.
I used FLutter_datetime_picker package.
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())
],
),
);
}
}
Upvotes: 3
Views: 12521
Reputation: 209
use this code
DateTime date1 = DateTime.now();
DateTime date2 = DateTime.now().add(Duration(days: 1));
Future<int> getDifference(DateTime date1,DateTime date2) async {
print('date1 $date1');
print('date2 $date2');
print("${date1.difference(date2).inHours}");
return date1.difference(date2).inHours;
}
Upvotes: 0
Reputation: 10963
You should put the variables outside of the build()
method, because when you call setState()
the build()
method is called again.
You could initialize variables inside the initState()
method, or in this case, you could just declare them with initialization.
Upvotes: 2
Reputation: 3157
You can calculate the difference when you select new date in onConfirm
method like this:
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),
],
),
);
}
}
Upvotes: 4