How to create a timer in Flutter using Provider

How to create a timer in Flutter using Provider

Learn how to effortlessly build a timer in Flutter using the Provider package. This step-by-step guide will demonstrate how to manage state efficiently and create a fully functional timer application in just a few lines of code. Enhance your Flutter skills and boost your app development with this easy-to-follow tutorial! This is a step-by-step guide to how to create a timer in Flutter using the provider package.

Step 1: Set up a new Flutter project Create a new Flutter project using your preferred IDE (e.g., Android Studio, VS Code) or the command line:

Step 2: Update dependencies Open the pubspec.yaml file in your project and add the provider package, which we’ll use for managing the state of the timer:

dependencies:
  flutter:
    sdk: flutter
  provider: ^5.0.0

Then, run flutter pub get to fetch the new dependency.

Step 3: Create the TimerModel class We’ll create a separate model class to manage the state of the timer. In this case, the TimerModel class will contain information about the remaining time and the functionality to start/stop the timer.

Create a new file named timer_model.dart in the lib folder and add the following code:

import 'dart:async';

import 'package:flutter/foundation.dart';

class TimerModel extends ChangeNotifier {
  Duration _remainingTime = Duration.zero;
  Timer? _timer;

  Duration get remainingTime => _remainingTime;

  bool get isRunning => _timer != null;

  void startTimer(Duration duration) {
    if (!isRunning) {
      _remainingTime = duration;
      _timer = Timer.periodic(Duration(seconds: 1), (_) {
        if (_remainingTime.inSeconds > 0) {
          _remainingTime -= Duration(seconds: 1);
          notifyListeners();
        } else {
          stopTimer();
        }
      });
      notifyListeners();
    }
  }

  void stopTimer() {
    _timer?.cancel();
    _timer = null;
    notifyListeners();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}

Step 4: Implement the Timer UI Now, let’s create the UI for the timer. Open the main.dart file in the lib folder and replace the code with the following:

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

import 'timer_model.dart';

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

class TimerApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => TimerModel(),
      child: MaterialApp(
        title: 'Timer App',
        home: TimerScreen(),
      ),
    );
  }
}

class TimerScreen extends StatelessWidget {
  final TextEditingController _controller = TextEditingController();
  Duration _parseDuration(String input) {
    final parts = input.split(':');
    return Duration(
      hours: int.parse(parts[0]),
      minutes: int.parse(parts[1]),
      seconds: int.parse(parts[2]),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Countdown Timer'),
      ),
      body: Center(
        child: Consumer<TimerModel>(
          builder: (context, timer, _) {
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (timer.isRunning)
                  Text(
                    '${timer.remainingTime.inHours.toString().padLeft(2, '0')}:${(timer.remainingTime.inMinutes % 60).toString().padLeft(2, '0')}:${(timer.remainingTime.inSeconds % 60).toString().padLeft(2, '0')}',
                    style: TextStyle(fontSize: 50),
                  ),
                SizedBox(height: 20),
                if (!timer.isRunning)
                  Container(
                    width: 200,
                    child: TextField(
                      controller: _controller,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(labelText: 'Enter duration (HH:mm:ss)'),
                    ),
                  ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    if (timer.isRunning) {
                      timer.stopTimer();
                    } else {
                      final input = _controller.text;
                      if (input.isNotEmpty) {
                        final duration = _parseDuration(input);
                        timer.startTimer(duration);
                      }
                    }
                  },
                  child: Text(timer.isRunning ? 'Stop Timer' : 'Start Timer'),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

Step 5: Run the app You can now run the app using flutter run in the terminal or by clicking the run button in your IDE. The app will open, allowing you to enter a duration (in HH:mm:ss format) and start the countdown timer.

When you start the timer, it will display the remaining time, and you can stop it at any point by pressing the “Stop Timer” button.

This code demonstrates a simple countdown timer using the provider package for state management. Feel free to enhance the UI or add more features as per your requirements. Happy coding!

Related Queries: timer in flutter, flutter timer, how to, count down timer in flutter, countdown timer using provider flutter

5/5 (1 vote)
Share to:
Scroll to Top