如何在Flutter中使用SharedPreferences保存DateFormat? [英] How to save DateFormat with SharedPreferences in Flutter?

查看:135
本文介绍了如何在Flutter中使用SharedPreferences保存DateFormat?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的问题:在进行比较后,我尝试使用SharedPreferences保存日期,但是返回null

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


推荐答案

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

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:

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

saving: prefs.setString('dateTimeLastClicked', currentTime);

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

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

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!

这篇关于如何在Flutter中使用SharedPreferences保存DateFormat?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆