文字颤动倒计时

时间:2019-05-14 18:59:59

标签: dart flutter

我们需要在Flutter中创建一个5分钟的倒计时文本对象,一旦倒数达到零,我们就需要启动一个新屏幕。这是当前代码:

 Container(
                                    margin: EdgeInsets.only(left: 0.0,top: 60.0, bottom: 50.0, right:0.0),    
                                    child: Text(

                '5:00', style: new TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 100.0 ))
              ,

                                     ), 

1 个答案:

答案 0 :(得分:1)

我通常不只是发布示例代码,但我的想法是扑朔迷离。因此,这是我关于如何实现此功能的快速建议:

class _MyHomePageState extends State<MyHomePage> {
  TickViewModel _viewModel; 
  int _seconds;
  StreamSubscription<int> _tickSubscription;

  @override
  void initState() {
    super.initState();
    _viewModel = TickViewModel();
    _tickSubscription = _viewModel._tickStream.listen((newTime) {
      if (newTime == 0) {
        //TODO: DO THE SCREEN CHANGE HERE;
      }
      setState(() {
        _seconds = newTime;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("My Flutter App"),
          backgroundColor: Colors.red,
        ),
        body: Text(_computeTime()));
  }

  String _computeTime() {
    if (_seconds == null) {
      return "-";
    }
    String minutes = "${_seconds ~/ 60}".padLeft(2, "0");
    String seconds = "${_seconds % 60}".padLeft(2, "0");
    return "$minutes:$seconds";
  }

  @override
  void dispose() {

    //We cleanup the stuffs here
    _tickSubscription.cancel();
    _viewModel.destroy();
    super.dispose();
  }
}

class TickViewModel {
  static const int _fiveMinutes = 5 * 60;
  StreamController<int> _ticker;

  Stream<int> get _tickStream => _ticker.stream;

  Timer _timer;
  final int seconds;
  int _internalSeconds;

  TickViewModel({this.seconds = _fiveMinutes}) : _internalSeconds = seconds {
    _ticker = StreamController(onListen: () {
      //start timer only when we have a subscriber
      _startTimer();
    }, onCancel: () {
      _timer.cancel();
    });
  }

  void _startTimer() {
    //start timer to tick every 1 second
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _internalSeconds -= 1;
      if (_internalSeconds < 0) {
        _timer.cancel();
      } else {
        _ticker.add(_internalSeconds);
      }
    });
  }

  void destroy() {
    _ticker.close();
    _timer.cancel();
  }
}