World Time App, A Flutter Mini Project with Source Code

A Basic Flutter application, that shows users the time around the world. This is a basic application beginners can use to practice Flutter skills. Users can use the application to learn about the time around the world. I used the World Time API to get the time in all cities. This makes the application completely modular. The time of any city can be added using only a few lines of code.

What is World Time API?

World Time API is a simple web service which returns the local-time for a given time zone as either JSON or plain-text. Some additional information is provided, such as whether that time zone is currently in Daylight Savings Time, when DST starts and ends, the UTC offset, etc.

Downloads

Download the following images :

Source Code

  • Create a flutter app using flutter create time app in the command terminal.
  • Go inside the time app folder.
  • Inside the time app folder make a assets folder, inside the folder add the above downloads.
  • Now go inside the time app / lib and add the following .dart files :
  • time app/lib/main.dart
import 'package:flutter/material.dart';
import 'package:world_time/loading.dart';

void main() => runApp(MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (context) => const Loading(),
      },
    ));
  • time app/lib/choose_location.dart
import 'package:flutter/material.dart';
import 'package:world_time/world_time.dart';

class ChooseLocation extends StatefulWidget {
  final Function(WorldTime) updateWorldTime;
  const ChooseLocation({required this.updateWorldTime, Key? key})
      : super(key: key);

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

class _ChooseLocationState extends State<ChooseLocation> {
  List<WorldTime> locations = [
    WorldTime(url: 'Europe/London', location: 'London', flag: 'uk.png'),
    WorldTime(url: 'Europe/Berlin', location: 'Athens', flag: 'greece.png'),
    WorldTime(url: 'Africa/Cairo', location: 'Cairo', flag: 'egypt.png'),
    WorldTime(url: 'Africa/Nairobi', location: 'Nairobi', flag: 'kenya.png'),
    WorldTime(url: 'America/Chicago', location: 'Chicago', flag: 'usa.png'),
    WorldTime(url: 'America/New_york', location: 'New york', flag: 'usa.png'),
    WorldTime(url: 'Asia/Seoul', location: 'Seoul', flag: 'south_korea.png'),
    WorldTime(url: 'Asia/Jakarta', location: 'Jakarta', flag: 'indonesia.png'),
    WorldTime(url: 'Africa/Lagos', location: 'Lagos', flag: 'nigeria.png'),
    WorldTime(url: 'Australia/Adelaide', location: 'Adelaide', flag: 'australia.jpg'),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        backgroundColor: Colors.blue[900],
        title: const Text('Choose a Location'),
        centerTitle: true,
        elevation: 0,
      ),
      body: ListView.builder(
          itemCount: locations.length,
          itemBuilder: (context, index) {
            return Padding(
              padding: const EdgeInsets.symmetric(
                vertical: 1.0,
                horizontal: 4.0,
              ),
              child: Card(
                child: ListTile(
                  onTap: () {
                    Navigator.pop(context);
                    widget.updateWorldTime(
                      locations[index],
                    );
                  },
                  title: Text(
                    locations[index].location,
                  ),
                  leading: CircleAvatar(
                    backgroundImage: AssetImage(
                      'assets/${locations[index].flag}',
                    ),
                  ),
                ),
              ),
            );
          }),
    );
  }
}
  • time app/lib/home.dart
import 'package:flutter/material.dart';
import 'package:world_time/choose_location.dart';
import 'package:world_time/world_time.dart';

class Home extends StatefulWidget {
  final WorldTime worldTime;
  const Home({required this.worldTime, Key? key}) : super(key: key);

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

class _HomeState extends State<Home> {
  WorldTime worldTime = WorldTime(
    location: 'Berlin',
    flag: 'germany.png',
    url: 'Europe/Berlin',
    // time: time,
  );

  @override
  void initState() {
    worldTime = widget.worldTime;
    super.initState();
  }

  // Map data = {};
  @override
  Widget build(BuildContext context) {
    // data = ModalRoute.of(context).settings.arguments;
    // print(data);
    // set background
    String bgImage = worldTime.isDaytime ?? true ? 'day.png' : 'night.png';
    Color bgcolor = worldTime.isDaytime ?? true ? Colors.blue : Colors.indigo;

    return Scaffold(
      backgroundColor: bgcolor,
      body: Container(
        decoration: BoxDecoration(
            image: DecorationImage(
          image: AssetImage('assets/$bgImage'),
          fit: BoxFit.cover,
        )),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(0, 120.0, 0, 0),
          child: Column(
            children: <Widget>[
              TextButton.icon(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => ChooseLocation(
                        updateWorldTime: (WorldTime newWorldTime) async {
                          worldTime = newWorldTime;
                          await worldTime.getTime();
                          setState(() {});
                        },
                      ),
                    ),
                  );
                },
                icon: Icon(
                  Icons.edit_location,
                  color: Colors.grey[300],
                ),
                label: Text(
                  'Edit Location',
                  style: TextStyle(
                    color: Colors.grey[300],
                  ),
                ),
              ),
              const SizedBox(height: 20.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    // data['location']
                    worldTime.location,
                    // }
                    style: const TextStyle(
                      fontSize: 28.0,
                      letterSpacing: 2.0,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20.0),
              Text(
                worldTime.time ?? '',
                style: const TextStyle(
                  fontSize: 66.0,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  • time app/lib/loading.dart
import 'package:flutter/material.dart';
import 'package:world_time/world_time.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'home.dart';
class Loading extends StatefulWidget {
  const Loading({Key? key}) : super(key: key);

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

class _LoadingState extends State<Loading> {



   void setupWorldTime() async{
    // String time = await WorldTime.getTime(url);
    WorldTime instance = WorldTime(
      location: 'Berlin',
      flag: 'germany.png',
      url: 'Europe/Berlin',
      // time: time,
    );
    await instance.getTime();
    Navigator.pushReplacement(context,
      MaterialPageRoute(builder: (context) => Home(worldTime: instance)),
    );

  }


  @override
  void initState() {
    super.initState();
    setupWorldTime();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue[900],
      body: const Center(
        child: SpinKitRotatingCircle(
          color: Colors.white,
          size: 50.0,
        ),
      ),
    );
  }
}
  • time app/lib/world_time.dart
import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';

class WorldTime {
  String location; // location name for the UI
  String? time; // the time in that location
  String flag; // url to an asset flag icon
  String url; // location url for api endpoint
  bool? isDaytime; // true or false if daytime or not

  WorldTime({
    required this.location,
    required this.flag,
    required this.url,
    this.time,
  });

  Future<void> getTime() async {
    try {
      // make request
      Response response = await get(
        Uri.parse('http://worldtimeapi.org/api/timezone/$url'),
      );
      Map data = jsonDecode(response.body);
      //print(data);

      //get properties from data
      String datetime = data['datetime'];
      String offset = data['utc_offset'].substring(1, 3);
      //print(datetime);
      //print(offset);

      //create DataTime object
      DateTime now = DateTime.parse(datetime);
      now = now.add(Duration(hours: int.parse(offset)));
      // set the time property
      isDaytime = now.hour > 6 && now.hour < 20 ? true : false;
      time = DateFormat.jm().format(now);
    } catch (e) {
      time = 'could not get time data';
    }
  }
}

Output

SHARE World Time App, A Flutter Mini Project with Source Code

You may also like...

Leave a Reply

Your email address will not be published.

Share