Search code examples
androiddartflutterflutter-layoutflutter-test

How to Set Timer Countdown in Flutter for 30 Second with OnPressed FAB Button?


Currently, I have write codes for making up the counter app with two buttons. 1 raised button to reset and one fab button for increment counter.

is it possible to add the countdown timer to implement on FAB button? When FAB button clicks 20-second countdown timer start.

Also, I have found below thread for the same type of function implement. But I don't where to put codes in my app to implement countdown work on FAB button.

How to make a countdown in flutter?

import 'package:flutter/material.dart';
import 'dart:ui';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Counter App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Counter App'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  int _counter = 0;
  AnimationController controller;
  bool _isButtonDisabled;

  Duration get duration => controller.duration * controller.value;

  bool get expired => duration.inSeconds == 0;

  @override
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 20),
    );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'number $_counter added',
            ),
            AnimatedBuilder(
                animation: controller,
                builder: (BuildContext context, Widget child) {
                  return new Text(
                    '${duration.inSeconds}',
                    style: new TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 50.0,
                    ),
                  );
                }),
            new Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                new RaisedButton(
                  padding: const EdgeInsets.all(15.0),
                  textColor: Colors.white,
                  color: Colors.redAccent,
                  onPressed: () {
                    setState(() {
                      controller.reset();
                      _counter = 0;
                    });
                  },
                  child: new Text("Reset"),
                ),
                new RaisedButton(
                  onPressed: () => setState(() {
                    controller.reverse(from: 1);
                  }),
                  textColor: Colors.white,
                  color: Colors.purple,
                  padding: const EdgeInsets.all(15.0),
                  child: new Text(
                    "Start",
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Container(
          height: 50.0,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() {
          _counter++;
        }),
        tooltip: 'Increment Counter',
        child: Icon(Icons.add),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }
}

Solution

  • try the following:

    import 'package:flutter/material.dart';
    import 'dart:ui';
    import 'dart:async';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Counter App',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Counter App'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
      int _counter = 0;
      AnimationController controller;
    
      Duration get duration => controller.duration * controller.value;
    
      bool get expired => duration.inSeconds == 0;
    
      @override
      void initState() {
        controller = AnimationController(
          vsync: this,
          duration: Duration(seconds: 20),
        );
    
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                AnimatedBuilder(
                  animation: controller,
                builder: (BuildContext context, Widget child) {
                  return new Text(
                    '${duration.inSeconds}',
                    style: new TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 50.0,
                    ),
                  );
                }),
                new Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    new RaisedButton(
                      padding: const EdgeInsets.all(15.0),
                      textColor: Colors.white,
                      color: Colors.redAccent,
                      onPressed: () {
                        setState(() {
                          controller.reset();
                        });
                      },
                      child: new Text("Reset"),
                    ),
                  ],
                ),
              ],
            ),
          ),
          bottomNavigationBar: BottomAppBar(
            child: Container(
              height: 50.0,
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () => setState(() {
    
              controller.reverse(from: 1);
                }),
            tooltip: 'Increment Counter',
            child: Icon(Icons.add),
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        );
      }
    }