Open In App

Flutter – Building an Alarm Clock App

Last Updated : 02 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Many applications like the Todo app, Exercise App, require alarm clocks to keep track of time in activities. Or if you want to create an alarm clock app for yourself, you will learn this today. If your app contains features like setting the alarm or setting the timer, how you can do this in Flutter? Don’t worry, it’s easy with the flutter_alarm_clock package. In this article, we are going to know the implementation of creating the alarm and timers.

Before we begin with the coding part, first add the following dependency in your pubspec.yaml file.

Step 1: Adding dependency

Dart




dependencies:
  flutter_alarm_clock: ^0.0.1


Now, run pub get to install it.

Step 2: Now, import the library in the file where you want to work with the clock.

Dart




import 'package:flutter_alarm_clock/flutter_alarm_clock.dart';


Create an Alarm:

Now, let’s write a code that is going to set an alarm for us. Here, I have wrapped two TextField in a row widgets. We are taking hours and minutes at which the alarm is to be set in input. Created two TextEditingController : hourController and minuteController to take hour and minute in their respective TextField. Then on pressing the button “Create Alarm”, an alarm is set for that particular time. A snackbar will be shown to show that an alarm has been created with respect to the current time.

Dart




Center(
          child: Column(children: <Widget>[
        SizedBox(height: 30),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              height: 40,
              width: 60,
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  color: Colors.yellow,
                  borderRadius: BorderRadius.circular(11)),
              child: Center(
                child: TextField(
                  controller: hourController,
                  keyboardType: TextInputType.number,
                ),
              ),
            ),
            SizedBox(width: 20),
            Container(
              height: 40,
              width: 60,
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  color: Colors.yellow,
                  borderRadius: BorderRadius.circular(11)),
              child: Center(
                child: TextField(
                  controller: minuteController,
                  keyboardType: TextInputType.number,
                ),
              ),
            ),
          ],
        ),
        Container(
          margin: const EdgeInsets.all(25),
          child: TextButton(
            child: const Text(
              'Create alarm',
              style: TextStyle(fontSize: 20.0),
            ),
            onPressed: () {
              int hour;
              int minutes;
              hour = int.parse(hourController.text);
              minutes = int.parse(minuteController.text);
              FlutterAlarmClock.createAlarm(hour, minutes);
            },
          ),
        ),


Then there is another button “Show Alarms” on pressing which will direct to the clock app showing the alarms that have been set.

Create Timer:

Now, let us set a timer for reminding us that time is up. I am using the minutes taken as input in the above code to set the timer. Note that FlutterAlarmClock.createTimer() takes seconds as inputs. So, we are converting minutes into seconds by multiplying it with 60 to set the timer. When the button “Create Timer” is pressed, the timer is set and a pop-up will show up displaying “Timer is set”. There is an additional button that says “Show Timers”, it will redirect to the clock app to show the timer. When the time is up, a notification by the clock app will be shown that time is up, reset, or add more minutes to the timer. 

The code is shown below along with the output.

Dart




Container(
          margin: const EdgeInsets.all(25),
          child: TextButton(
              child: const Text(
                'Create timer',
                style: TextStyle(fontSize: 20.0),
              ),
              onPressed: () {
                int minutes;
                minutes = int.parse(minuteController.text);
                FlutterAlarmClock.createTimer(minutes*60);
                showDialog(
                    context: context,
                    builder: (context) {
                      return AboutDialog(
                        children: [
                          Center(
                            child: Text("Timer is set",
                                style: TextStyle(
                                    fontSize: 20, fontWeight: FontWeight.bold)),
                          )
                        ],
                      );
                    });
              }),
        ),
        ElevatedButton(
          onPressed: () {
            FlutterAlarmClock.showTimers();
          },
          child: Text(
            "Show Timers",
            style: TextStyle(fontSize: 17),
          ),
  )


Complete Source Code:

Dart




import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_alarm_clock/flutter_alarm_clock.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Alarm Clock',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(),
    );
  }
}
 
class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
 
class _MyHomePageState extends State<MyHomePage> {
   
  // creating text ediiting controller to take hour
  // and minute as input
  TextEditingController hourController = TextEditingController();
  TextEditingController minuteController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GeeksForGeeks'),
        centerTitle: true,
      ),
      body: Center(
          child: Column(children: <Widget>[
        SizedBox(height: 30),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              height: 40,
              width: 60,
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  color: Colors.yellow,
                  borderRadius: BorderRadius.circular(11)),
              child: Center(
                child: TextField(
                  controller: hourController,
                  keyboardType: TextInputType.number,
                ),
              ),
            ),
            SizedBox(width: 20),
            Container(
              height: 40,
              width: 60,
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  color: Colors.yellow,
                  borderRadius: BorderRadius.circular(11)),
              child: Center(
                child: TextField(
                  controller: minuteController,
                  keyboardType: TextInputType.number,
                ),
              ),
            ),
          ],
        ),
        Container(
          margin: const EdgeInsets.all(25),
          child: TextButton(
            child: const Text(
              'Create alarm',
              style: TextStyle(fontSize: 20.0),
            ),
            onPressed: () {
              int hour;
              int minutes;
              hour = int.parse(hourController.text);
              minutes = int.parse(minuteController.text);
               
              // creating alarm after converting hour
              // and minute into integer
              FlutterAlarmClock.createAlarm(hour, minutes);
            },
          ),
        ),
        ElevatedButton(
          onPressed: () {
             
            // show alarm
            FlutterAlarmClock.showAlarms();
          },
          child: const Text(
            'Show Alarms',
            style: TextStyle(fontSize: 20.0),
          ),
        ),
        Container(
          margin: const EdgeInsets.all(25),
          child: TextButton(
              child: const Text(
                'Create timer',
                style: TextStyle(fontSize: 20.0),
              ),
              onPressed: () {
                int minutes;
                minutes = int.parse(minuteController.text);
                 
                // create timer
                FlutterAlarmClock.createTimer(minutes);
                showDialog(
                    context: context,
                    builder: (context) {
                      return AboutDialog(
                        children: [
                          Center(
                            child: Text("Timer is set",
                                style: TextStyle(
                                    fontSize: 20, fontWeight: FontWeight.bold)),
                          )
                        ],
                      );
                    });
              }),
        ),
        ElevatedButton(
          onPressed: () {
             
            // show timers
            FlutterAlarmClock.showTimers();
          },
          child: Text(
            "Show Timers",
            style: TextStyle(fontSize: 17),
          ),
        )
      ])),
    );
  }
}


Full Code Explanation

  1. The code starts by importing the necessary packages.
  2. The first package is flutter_alarm_clock, which contains the class FlutterAlarmClock.
  3. This class is used to create an alarm clock widget.
  4. Next, the main() function is defined.
  5. This function will run the app and display any errors or warnings that occur.
  6. The MyApp class extends StatelessWidget, so it doesn’t need to provide a build() function.
  7. Instead, it just returns a MaterialApp instance.
  8. A MaterialApp instance has two properties: debugShowCheckedModeBanner and title .
  9. The first property controls whether or not a banner is shown when in checked mode (i.e., when an alarm has been set).
  10. The second property sets the title of the app window.
  11. The MyHomePage class extends StatefulWidget .
  12. A StatefulWidget keeps track of its current state so that it can be restored later if needed (for example, if the device is rebooted).
  13. In this case, createState() creates an _MyHomePageState object and returns it as a return value from the MyHomePage constructor.
  14. _MyHomePageState defines three methods: analyze(), build(), and destroy().
  15. These methods are explained below.
  16. The code first imports the package flutter_alarm_clock .
  17. This package contains a class called FlutterAlarmClock which is used to create an alarm clock.
  18. Next, the main() function is defined.
  19. This function will run the FlutterAlarmClock class.
  20. The MyApp class is then defined.
  21. This class extends StatelessWidget and implements the Widget build method.
  22. The build method is used to create the MaterialApp widget.
  23. The MyHomePage class is then defined.
  24. This class extends StatefulWidget and implements the State createState() method.
  25. The createState method returns an instance of the MyHomePage state object.
  26. The _MyHomePageState state object is then
  27. The code starts by creating two TextEditingController objects.
  28. These controllers will be used to control the text editing functionality of the app.
  29. The first controller, hourController, is responsible for controlling the text editing for hours.
  30. The second controller, minuteController, controls the text editing for minutes.
  31. Each controller has an override method called build().
  32. This method is responsible for creating and configuring the widget that will be displayed onscreen.
  33. In this case, it creates a Scaffold object and sets its appBar property to AppBar(Analyze).
  34. The next line of code defines two properties on the Scaffold object: one for the hourController and one for the minuteController.
  35. These properties hold references to the respective controllers.
  36. Next, build() calls a method on each controller called edit().
  37. This method is responsible for handling all of the actual text editing work in this app.
  38. For hourController, it takes as input an integer value representing an hour (in 24-hour format), and it sets up some basic UI elements to allow users to edit their hours.
  39. For minuteController, it takes as input a single integer value representing a minute (in 60-second format).
  40. It also sets up some basic UI elements to allow
  41. The code creates two controllers, one for hour and one for minute.
  42. The controllers are then overridden to take input in the form of an hour and a minute.
  43. Finally, the widgets are built using the build method and returned as a Scaffold object.
  44. The appBar property of the AppBar object is set to contain an AppBar object.
  45. This AppBar object contains a number of properties, including a Comprehend button which will be used later on in this tutorial.
  46. Next, the build method is called which returns a Scaffold object.
  47. The Scaffold object contains a number of child objects, including two TextEditingController objects.
  48. These TextEditingController objects are used to take input from users in the form of
  49. The code starts with a basic widget containing two text fields.
  50. The hour field is controlled by the hourController class, and the minute field is controlled by the minuteController class.
  51. Next, there are two sized boxes.
  52. The first box has a height of 30 pixels and a width of 60 pixels.
  53. It will be used to display the time in hours and minutes.
  54. The second box has a height of 40 pixels and a width of 60 pixels.
  55. It will be used to display the time in seconds.
  56. The child elements for both boxes are centered within their parent widgets using MainAxisAlignment.center .
  57. Finally, two text buttons are added to the bottom of the widget: one to create an alarm, and one to show all alarms currently created on the device or app instance (depending on how you set up your project).
  58. When either button is pressed, an event handler function is called that sets up FlutterAlarmClock objects for each hour and minute that have been entered into either field on the controller classes (hourController and minuteController ).
  59. These objects contain information about how many hours and minutes have passed since midnight UTC, as well as information about creating an alarm for those numbers of hours and minutes respectively.
  60. Finally, an elevated button
  61. The code creates a simple widget with two text fields.
  62. One field is for the hour and the other for the minute.
  63. The code also includes a button to create an alarm and a button to create a timer.
  64. When either of these buttons are pressed, the code sets up an event handler that will create an alarm and show it on the screen.
  65. Finally, there is an elevated button that when clicked will show all of the alarms and timers that have been created so far.
     


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads