如何在 flutter 中使用 sharedpref 保存最大持续时间?

How to save max duration with sharedpref in flutter?

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

这是代码,谢谢 (@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)    ;

           }
       }
     ); 
  }

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

使用 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";
  }
}