Flutter - Create a countdown widget

前端 未结 5 1923
没有蜡笔的小新
没有蜡笔的小新 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:46

    Countdown example using stream, not using setState(...) therefore its all stateless.

    this borrow idea from example 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 {
      final Stream _stream;
    
      CounterScreenStream(int initialValue)
          : this._stream = createStream(initialValue);
    
      @override
      StreamSubscription 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 createStream(int initialValue) {
        var cd = new CountDown(new Duration(seconds: initialValue));
        return cd.stream;
      }
    }
    

    The difference from stateful is that reload the app will restart counting. When using stateful, in some cases, it may not restart when reload.

提交回复
热议问题