Getting Started with Flutter – Creating a Timer App

In this blog post, I will guide you through creating a simple timer app using Flutter. This will help you get familiar with Flutter’s basic concepts and structure.

Prerequisites

Before we dive in, make sure you have the following installed:

  1. Flutter SDK
  2. Android Studio or Visual Studio Code with Flutter and Dart plugins
  3. A basic understanding of Dart programming language

Step 1: Setting Up the Flutter Project

Open your terminal or command prompt and create a new Flutter project:

flutter create timer_app

Navigate to the project directory:

cd timer_app

Open the project in your preferred code editor (VS Code or Android Studio).

Step 2: Creating the Timer App

Modifying the main.dart File

Open the lib/main.dart file and replace its content with the following code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

class TimerPage extends StatefulWidget {
  @override
  _TimerPageState createState() => _TimerPageState();
}

class _TimerPageState extends State<TimerPage> {
  // Define a variable to keep track of the timer's duration.
  Duration _duration = Duration();
  // Define a variable to manage the Timer.
  Timer? _timer;

  // Function to start the timer.
  void _startTimer() {
    // Check if a timer is already running, if so, stop it.
    if (_timer != null) {
      _timer!.cancel();
    }
    // Set the timer to update every second.
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        // Increase the duration by 1 second.
        _duration += Duration(seconds: 1);
      });
    });
  }

  // Function to stop the timer.
  void _stopTimer() {
    // Cancel the timer if it is running.
    if (_timer != null) {
      _timer!.cancel();
    }
  }

  // Function to reset the timer.
  void _resetTimer() {
    setState(() {
      // Set the duration back to zero.
      _duration = Duration();
      // Cancel the timer if it is running.
      if (_timer != null) {
        _timer!.cancel();
      }
    });
  }

  @override
  void dispose() {
    // Cancel the timer if it is running when the widget is disposed.
    if (_timer != null) {
      _timer!.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Get the minutes and seconds from the duration.
    final minutes = _duration.inMinutes.remainder(60);
    final seconds = _duration.inSeconds.remainder(60);

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Timer App'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // Display the timer in MM:SS format.
            Text(
              '$minutes:${seconds.toString().padLeft(2, '0')}',
              style: TextStyle(fontSize: 48),
            ),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                // Button to start the timer.
                ElevatedButton(
                  onPressed: _startTimer,
                  child: Text('Start'),
                ),
                SizedBox(width: 10),
                // Button to stop the timer.
                ElevatedButton(
                  onPressed: _stopTimer,
                  child: Text('Stop'),
                ),
                SizedBox(width: 10),
                // Button to reset the timer.
                ElevatedButton(
                  onPressed: _resetTimer,
                  child: Text('Reset'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Code Explanation

Let’s break down the code step-by-step:

Main Function and MyApp Class:

    • The main() function is the entry point of the app, which calls runApp() to start the application.
    • MyApp is a stateless widget that sets up the MaterialApp with a title, theme, and home page (TimerPage).
    1. TimerPage Stateful Widget:
    • TimerPage is a stateful widget because the timer’s state (duration) needs to change over time.
    • _TimerPageState manages the state of TimerPage.

    State Variables:

      • _duration: A Duration object to keep track of the elapsed time.
      • _timer: A Timer object to handle the periodic updates.

      Timer Control Functions:

        • _startTimer(): Starts the timer and updates the duration every second.
        • _stopTimer(): Stops the timer if it is running.
        • _resetTimer(): Resets the duration to zero and stops the timer if it is running.

        dispose() Method:

          • This method is called when the widget is disposed of. It cancels the timer to prevent memory leaks.

          build() Method:

            • The build method constructs the UI. It includes:
              • An AppBar with the app title.
              • A Center widget containing a Column that displays the timer and control buttons (Start, Stop, Reset).
              • The timer is displayed in MM:SS format, and the buttons call the respective control functions when pressed.

            Step 3: Running the App

            To run the app, use the following command in your terminal:

            flutter run

            Alternatively, you can use your code editor’s built-in tools to run the app on an emulator or physical device.

            You should see something like this:

            The flutter app running as a windows application.