首页 文章

颤动 - 创建倒计时小部件

提问于
浏览
6

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

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

然而, Value 变化非常奇怪而且根本不光滑 . 它开始抽搐 . 任何其他方法或修复?

4 回答

  • 1

    应该从 State 对象的 initState() 方法调用 countdown() 方法 .

    class _CountdownState extends State<CountdownWidget> {
    
      int val = 3;
      CountDown cd;
    
      @override
      void initState() {
        super.initState();
        countdown();
      }
    ...
    

    来自Flutter docsinitState() 的描述:

    框架调用initState . State的子类应覆盖initState以执行依赖于BuildContext或窗口小部件的一次性初始化,这些初始化分别在调用initState方法时可用作上下文和窗口小部件属性 .

    这是一个完整的工作示例:

    import 'dart:async';
    import 'package:flutter/material.dart';
    import 'package:countdown/countdown.dart';
    
    void main() {
      runApp(new MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Countdown Demo',
          theme: new ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: new MyHomePage(),
        );
      }
    }
    
    
    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new CountdownWidget();
      }
    }
    
    class _CountdownState extends State<CountdownWidget> {
    
      int val = 3;
      CountDown cd;
    
      @override
      void initState() {
        super.initState();
        countdown();
      }
    
      void countdown(){
        print("countdown() called");
        cd = new CountDown(new Duration(seconds: 4));
        StreamSubscription sub = cd.stream.listen(null);
        sub.onDone(() {
          print("Done");
        });
        sub.onData((Duration d) {
          if (val == d.inSeconds) return;
          print("onData: d.inSeconds=${d.inSeconds}");
          setState((){
            val = d.inSeconds;
          });
        });
      }
    
      @override
      build(BuildContext context){
        return new Scaffold(
          body: new Container(
            child: new Center(
              child: new Text(val.toString(), style: new TextStyle(fontSize: 150.0)),
            ),
          ),
        );
      }
    }
    
    class CountdownWidget extends StatefulWidget {
    
      @override
      _CountdownState createState() => new _CountdownState();
    }
    
  • 0

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

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

    使用流的倒计时示例,不使用 setState(...) 因此它的所有无状态 .

    借用例子flutter_stream_friends

    import 'dart:async';
    import 'package:flutter/material.dart';
    import 'package:countdown/countdown.dart';
    
    void main() {
      runApp(new MyApp());
    }
    
    class MyApp extends StatelessWidget {
      static String appTitle = "Count down";
    
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: appTitle,
          theme: new ThemeData(
            primarySwatch: Colors.purple,
          ),
          home: new StreamBuilder(
              stream: new CounterScreenStream(5),
              builder: (context, snapshot) => buildHome(
                  context,
                  snapshot.hasData
                      // If our stream has delivered data, build our Widget properly
                      ? snapshot.data
                      // If not, we pass through a dummy model to kick things off
                      : new Duration(seconds: 5),
                  appTitle)),
        );
      }
    
      // The latest value of the CounterScreenModel from the CounterScreenStream is
      // passed into the this version of the build function!
      Widget buildHome(BuildContext context, Duration duration, String title) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text(title),
          ),
          body: new Center(
            child: new Text(
              'Count down ${ duration.inSeconds }',
            ),
          ),
        );
      }
    }
    
    class CounterScreenStream extends Stream<Duration> {
      final Stream<Duration> _stream;
    
      CounterScreenStream(int initialValue)
          : this._stream = createStream(initialValue);
    
      @override
      StreamSubscription<Duration> listen(
              void onData(Duration event),
              {Function onError,
              void onDone(),
              bool cancelOnError}) =>
          _stream.listen(onData,
              onError: onError, onDone: onDone, cancelOnError: cancelOnError);
    
      // The method we use to create the stream that will continually deliver data
      // to the `buildHome` method.
      static Stream<Duration> createStream(int initialValue) {
        var cd = new CountDown(new Duration(seconds: initialValue));
        return cd.stream;
      }
    }
    

    与有状态的区别在于重新加载应用程序将重新开始计数 . 使用有状态时,在某些情况下,重新加载时可能无法重新启动 .

  • 1

    基于@ raju-bitter的答案,替代在倒计时流上使用async / await

    void countdown() async {
        cd = new CountDown(new Duration(seconds:4));
        await for (var v in cd.stream) {
          setState(() => val = v.inSeconds);
        }
      }
    

相关问题