我正在try 建立一个倒计时小工具.目前,我已经让这个 struct 运转起来了.我只为倒计时本身而苦苦挣扎.我使用倒计时插件try 了这种方法:

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)),
        ),
      ),
    );
  }
}

然而,值的变化非常奇怪,一点也不平滑.它开始抽搐.是否有其他方法或解决方案?

推荐答案

听起来您似乎是在try 显示一个随时间变化的动画文本小部件.我会使用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相关问答推荐

我们应该将多少代码放入构造函数中?

S,返回Future.sync()的函数和不需要等待的异步函数有什么区别?

如何在 Dart 游戏中重复听按键?

MappedListIterable 不是子类型

如何调整ShowDialog的子级大小

Flatter有数据绑定吗?

dart- 四舍五入

如何在 Flutter 中使用 Provider 显示来自 ChangeNotifier 的错误

如何在 flutter 中对json进行字符串化

Flutter 如何使用 ListTile 三行

Flutter – 连续两个文本,左边一个溢出

如何平移和zoom 图像?

Dart 中的动态类方法调用

Dart:如何判断变量类型是否为字符串

从 Dart Map 中删除选定的键

学习 Dart 好还是我必须使用基本的 javascript?

使用 Futures 时 .then() 和 .whenCompleted() 方法之间的区别?

Dart 中的外部是什么意思?

如何从 Dart 中的列表中获取随机元素?

如何在 Dart 中定义接口?