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

时间:2019-05-26 09:42:10

标签: flutter duration

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

这是代码谢谢(@ZeRj)

probabilities

我尝试了下面的代码,但是我不能将>与字符串一起使用,并试图解析int但不能与日期一起使用,并且我尝试使用regex提取每个小数,但是这很复杂,而且我有错误,但我没有了解。

  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";


  }

1 个答案:

答案 0 :(得分: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";
  }
}