dart - Flutter - 创建倒计时小部件

标签 dart flutter

我正在尝试构建一个倒计时小部件。目前,我的结构可以正常工作。我只与倒计时本身作斗争。我使用倒计时插件尝试了这种方法:

class _Countdown extends State<Countdown> {

  int val = 3;

  void countdown(){
    CountDown cd = new CountDown(new Duration(seconds: 4));

    cd.stream.listen((Duration d) {
      setState((){
        val = d.inSeconds;
      });
    });

  }

  @override
  build(BuildContext context){
    countdown();
    return new Scaffold(
      body: new Container(
        child: new Center(
          child: new Text(val.toString(), style: new TextStyle(fontSize: 150.0)),
        ),
      ),
    );
  }
}

但是,值的变化非常奇怪,而且一点也不平滑。它开始抽搐。还有其他方法或修复方法吗?

最佳答案

听起来您正在尝试显示随时间变化的动画文本小部件。我会使用 AnimatedWidgetStepTween确保倒计时只显示整数值。

countdown

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

class Countdown extends AnimatedWidget {
  Countdown({ Key key, this.animation }) : super(key: key, listenable: animation);
  Animation<int> animation;

  @override
  build(BuildContext context){
    return new Text(
      animation.value.toString(),
      style: new TextStyle(fontSize: 150.0),
    );
  }
}

class MyApp extends StatefulWidget {
  State createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
  AnimationController _controller;

  static const int kStartValue = 4;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: kStartValue),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.play_arrow),
        onPressed: () => _controller.forward(from: 0.0),
      ),
      body: new Container(
        child: new Center(
          child: new Countdown(
            animation: new StepTween(
              begin: kStartValue,
              end: 0,
            ).animate(_controller),
          ),
        ),
      ),
    );
  }
}

关于dart - Flutter - 创建倒计时小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44302588/

相关文章:

dart - 如何修复VSCode中dart:html的查找错误?

dart - 观察Polymer 1中列表中各项的属性更改

android - 如何从 Android 服务调用 Dart 代码?

json - 解析JSON( map 列表)将返回null

flutter - 如何使按钮宽度与父级匹配?

flutter - DropdownButtonFormField 将值重置为初始值

flutter - 如何在自定义文本字段中添加OnChange

dart - 示例代码在 Dart 编辑器中不起作用

dart - 如何使用 flutter 共享文件

firebase - 如何调用功能ASA应用程序在运行中运行?