How to save DateFormat with SharedPreferences in Flutter?

强颜欢笑 提交于 2019-12-24 10:57:53

问题


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.
    );
  }
}

回答1:


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!




回答2:


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;


来源:https://stackoverflow.com/questions/56112105/how-to-save-dateformat-with-sharedpreferences-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!