如何在flutter中使用sharedpref保存dateformat?

时间:2019-05-13 12:12:23

标签: flutter

你好,我试图计算每个小时按下按钮的次数。为此,当我按下按钮时,我将当前时间保存在变量中,以获取所按下按钮的小时数的引用;如果我第二次按下按钮,我想将当前时间与上次保存的时间进行比较知道时间是否变了。如果有其他时间,则将计数器重置为0,否则我将计数器增加。这样,我可以知道每个小时我按下了多少按钮。可能有一个更简单的解决方案。

我的问题:进行比较后,我尝试使用sharedpreference保存日期,但是返回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.
    );
  }
}

2 个答案:

答案 0 :(得分:2)

SharedPreferences putget方法需要将键作为字符串的第一个参数,将实际值作为第二个参数。该键用于映射值,以便可以找到它进行保存和加载。在您的实现中,密钥是根据值而变化的,因此它不能映射到现有数据,因此您得到null

选择唯一标识符,您的问题应按以下方式解决:

保存:prefs.setString('dateTimeLastClicked', currentTime);

正在加载:reftime_string = prefs.getString('dateTimeLastClicked');

此外:我建议您避免使用var-如果您使用显式类型,它将对您有很大帮助,因此,由于错误的类型假设等原因,您将获得较少的异常!

答案 1 :(得分:0)

您可以使用时间戳,而不是使用DateFormat将日期/时间保存在共享首选项中。

int timestamp = DateTime.now().millisecondsSinceEpoch;

final prefs = await SharedPreferences.getInstance();
prefs.setInt('myTimestampKey', timestamp);

然后,当您想再次找回它时,可以将时间戳转换回DateTime对象。

final prefs = await SharedPreferences.getInstance();
int timestamp = prefs.getInt('myTimestampKey');

DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);

您可以获取两个日期之间的时差作为持续时间:

DateTime before = DateTime.fromMillisecondsSinceEpoch(timestamp);
DateTime now = DateTime.now();
Duration timeDifference = now.difference(before);

只要有持续时间,就很容易获得分钟或小时数或其他任何数字。

int hours = timeDifference.inHours;