Flutter - Create a countdown widget

前端 未结 5 1918
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 20:58

I am trying to build a countdown widget. Currently, I got the structure to work. I only struggle with the countdown itself. I tried this approach using the countdown plugin:

5条回答
  •  野的像风
    2021-02-05 21:42

    The countdown() method should be called from the initState() method of the State object.

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

    Description of initState() from the Flutter docs:

    The framework calls initState. Subclasses of State should override initState to perform one-time initialization that depends on the BuildContext or the widget, which are available as the context and widget properties, respectively, when the initState method is called.

    Here is a full working example:

    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 {
    
      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();
    }
    

提交回复
热议问题