Flutter Time Picker with day/night animation

Published January 01, 2022

We all love animation. Imagine you showing your users how the sun rises and sets with the moon rising after when they change time of day. In this Flutter example we will see Flutter Time Picker with day night theme animation

Imagine no more because you can do it now. Because there's a special package made for that day nigth time picker

Now let's get started

Step 1: Create Flutter application

Step 2: Install the day night time Picker package  in your pubspec.yaml file

dependencies:
  day_night_time_picker: ^1.0.4+1

 

Step 3: Create a dart file and add below code

import 'package:flutter/material.dart';

import 'package:day_night_time_picker/day_night_time_picker.dart';

void main() => runApp(const Home());

class Home extends StatelessWidget {

  const Home({Key? key}) : super(key: key);

  @override

  Widget build(BuildContext context) {

    return const MaterialApp(

      home: MyApp(),

    );

  }

}

class MyApp extends StatefulWidget {

  const MyApp({Key? key}) : super(key: key);

  @override

  _MyAppState createState() => _MyAppState();

}

class _MyAppState extends State<MyApp> {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text('Plugin example app'),

      ),

      ),

    );

  }

}

 

Now we'll make our body. We want the time Picker to show wen we click the button

body: ElevatedButton(

        onPressed: () {

          Navigator.push(

              context, showPicker(value: _time, onChange: onTimeChanged));

        },

        child: const Text(

          "Open time picker",

          style: TextStyle(color: Colors.white),

        ),

 

In the above code. We have an on pressed function in our button. The button will navigate to the picker when it is clicked.

In our showPicker, we have some parameters like the value and the onChange property.

We need to define this.

So in our app state, above the override we will add these two codes

 

TimeOfDay _time = TimeOfDay.now();

  void onTimeChanged(TimeOfDay newTime) {

    setState(() {

      _time = newTime;

    });

  }

 

First we define the time of day which means it will display the current time. And the we create an onTimeChanged function which takes the time parameter. We are simple saying that when the time changes from our picker we should set the time we defined to the time change

As we move the slider to change the time, we see the animation

Flutter Time picker with day night animation theme

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

650 Views