I tried to count the number of pressed button for each hours. To do this When I pressed the button, I save the current time in a variable to have a reference of the hours of the pressed button, if I press a second time the button, I want to compare the current time with the previous time saved to know if the hours has changed. If there is a different time I reset the counter to 0, else I increase the counter. Like this I can know how much I pressed the button for each hours. There may be a simpler solution.
My problem : I tried to save the date with SharedPreferences, to after make a comparison, but it return null
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:intl/intl.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var currentTime = DateFormat('yyyy-MM-dd – kk:mm').format(DateTime.now());
var currentTime2 = DateFormat('yyyy-MM-dd – kk:mm').format(DateTime.now());
int consommation = 0;
String reftime_string;
//------------------------------------------------------------------------------------------------
save_refTime() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setString('$currentTime2', reftime_string);
});
load_refTime();
}
load_refTime() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
reftime_string = (prefs.getString('$currentTime2'));
});
}
//--------------------------------------------------------------------------------------------------------------
save_data() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
if (currentTime==reftime_string){
consommation++;
prefs.setInt('$currentTime''consommation', consommation); // creer un currenttime2 ajustable
}else{
consommation=0;
consommation++;
prefs.setInt('$currentTime''consommation', consommation); // creer un currenttime2 ajustable
}
});
load_data();
}
load_data() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
consommation = (prefs.getInt('$currentTime''consommation'));
});
}
void _incrementCounter() {
setState(() {
save_refTime();
save_data();
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$consommation',
style: Theme.of(context).textTheme.display1,
),
Text(
'$currentTime',
style: Theme.of(context).textTheme.display1,
),
Text(
'$reftime_string',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Rather than using DateFormat to save the date/time in shared preferences, you can use a timestamp.
int timestamp = DateTime.now().millisecondsSinceEpoch;
final prefs = await SharedPreferences.getInstance();
prefs.setInt('myTimestampKey', timestamp);
Then when you want to get it back again you can convert the timestamp back into a DateTime object.
final prefs = await SharedPreferences.getInstance();
int timestamp = prefs.getInt('myTimestampKey');
DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
You can get the difference between two dates as a Duration:
DateTime before = DateTime.fromMillisecondsSinceEpoch(timestamp);
DateTime now = DateTime.now();
Duration timeDifference = now.difference(before);
Once you have a duration, it is easy to get the number of minutes or hours or whatever.
int hours = timeDifference.inHours;
Recently I've been using the ISO 8601 Date and Time Format as a time stamp. Unlike milliseconds since epoch, the ISO 8601 date is human readable.
String timeStamp = DateTime.now().toIso8601String();
// 2020-04-17T11:59:46.405
DateTime dateTime = DateTime.parse('2020-04-17T11:59:46.405');
Unlike dateTime.toString()
, the ISO 8601 method doesn't have any spaces:
2020-04-17T11:59:46.405 // dateTime.toIso8601String()
2020-04-17 11:59:46.405 // dateTime.toString()
The SharedPreferences
put
and get
methods require a key as a String as its first parameter and the actual value as the second parameter. The key is used to map the value so it can be found to save and load. In your implementation the key is changing based on the value so it can't map to existing data and you get null
.
Choose unique identifier and your problem should be solved like:
saving: prefs.setString('dateTimeLastClicked', currentTime);
loading: reftime_string = prefs.getString('dateTimeLastClicked');
Also: I would recommend you to avoid using var
- It will help you a lot if you use explicit types so you will get less exceptions due to wrong type assumptions and so on!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With