【问题标题】:How to save max duration with sharedpref in flutter?如何在颤动中使用 sharedpref 保存最大持续时间?
【发布时间】:2019-10-12 05:18:35
【问题描述】:

仅当我的最后一个持续时间优于当前持续时间时,我才尝试使用 sharedpreference 保存持续时间,因此显示 MAX 持续时间。我的问题是我不知道如何比较两个字符串的持续时间。

这里是代码谢谢 (@ZeRj)

  load_lastPressString()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {

      final lastPressString = prefs.getString("lastButtonPress");
      _lastButtonPress = lastPressString!=null ? DateTime.parse(lastPressString) : DateTime.now();
      _updateTimer();
      _ticker = Timer.periodic(Duration(seconds:1),(_)=>_updateTimer());
    });
  }


  save_lastPressString()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      prefs.setString('_lastButtonPress', _lastButtonPress.toIso8601String());
    });
  }

  void _updateTimer() {
    final duration = DateTime.now().difference(_lastButtonPress);
    final newDuration = _formatDuration(duration);
    setState(() {
      _pressDuration = newDuration;
    });
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inDays)}:${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";


  }

我尝试了下面的代码,但我无法将 > 与字符串一起使用,并尝试解析 int 但无法使用日期解析,我尝试使用正则表达式提取每个小数,但这太复杂了,而且我有错误我没有明白。

  save_max_lastPress()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {

if(_lastButtonPress>Max_lastButtonPress)
               {
        prefs.setString('_max_lastPress', Max_lastButtonPress)    ;

           }
       }
     ); 
  }

【问题讨论】:

    标签: flutter duration


    【解决方案1】:

    为此,您必须将最大值保存为持续时间。

    使用prefs.setInt("maxDuration",maxDuration.toSeconds()) 将其保存为共享首选项中的 int 并使用

    加载它
    Duration(seconds: prefs.getInt("maxDuration")
    

    您可以简单地比较两个 Duration 实例。

    我编辑了最后一个例子来实现这个功能:

    import 'dart:async';
    import 'package:flutter/material.dart';
    import 'package:flutterfly/SharedPrefs.dart';
    import 'package:flutterfly/SharedPrefs.dart' as prefix0;
    
    class TestWidget extends StatefulWidget {
      @override
      _TestWidgetState createState() => _TestWidgetState();
    }
    
    class _TestWidgetState extends State<TestWidget> {
      DateTime _lastButtonPress;
      String _pressDuration;
      Timer _ticker;
      Duration _maxDuration;
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("Time since button pressed"),
              Text(_pressDuration),
              Text("Maximal Duration"),
              Text(_formatDuration(_maxDuration)),
              RaisedButton(
                child: Text("Press me"),
                onPressed: () {
                  _lastButtonPress = DateTime.now();
                  _updateTimer();
                  sharedPreferences.setString("lastButtonPress",_lastButtonPress.toIso8601String());
                },
              )
            ],
          ),
        );
      }
    
    
      @override
      void initState() {
        super.initState();
        //load max duration, if there is none start with 0
        _maxDuration = Duration(seconds:sharedPreferences.getInt("maxDuration")??0);
        final lastPressString = sharedPreferences.getString("lastButtonPress");
        _lastButtonPress = lastPressString!=null ? DateTime.parse(lastPressString) : DateTime.now();
        _updateTimer();
        _ticker = Timer.periodic(Duration(seconds:1),(_)=>_updateTimer());
      }
    
    
      @override
      void dispose() {
        _ticker.cancel();
        super.dispose();
      }
    
    
    
      void _updateTimer() {
        final duration = DateTime.now().difference(_lastButtonPress);
        //check for new max duration here
        Duration newMaxDuration = _maxDuration;
        if(duration> _maxDuration) {
          //save when current duration is a new max
          newMaxDuration = duration;
          sharedPreferences.setInt("maxDuration",newMaxDuration.inSeconds);
        }
        final newDuration =_formatDuration(duration);
        setState(() {
          _maxDuration = newMaxDuration;
          _pressDuration = newDuration;
        });
      }
    
      String _formatDuration(Duration duration) {
        String twoDigits(int n) {
          if (n >= 10) return "$n";
          return "0$n";
        }
    
        String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
        String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
        return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
      }
    }
    

    【讨论】:

    • 不完全是我搜索的内容,使用此代码它会在触发最大持续时间时停止计数器。我想让当前计时器工作,但如果我再次按下按钮,显示一个具有最大持续时间的新变量。目标是在所有持续时间记录之间始终显示最大持续时间。对不起,如果我不清楚:)
    • 对不起,你的意图错了。我用一个新例子编辑了我的答案
    • @ZeRj 你知道如何在共享首选项中设置过期时间而不是使用 Duration 吗?...例如...共享首选项中的数据将在 11:00:00 过期
    • @uyhaW 使用 date.toIso8601String() 函数并将字符串存储在共享首选项中。使用 DateTime.parse() 从字符串中恢复日期。
    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 2020-03-30
    • 2020-12-04
    • 2021-01-17
    • 2020-03-05
    • 2022-12-12
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多