小编典典

如何在Flutter中使用SharedPreferences保存DateFormat?

flutter

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

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

阅读 430

收藏
2020-08-13

共1个答案

小编典典

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

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

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

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

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

2020-08-13