DEV Community

Cover image for Build Prayer Times in Flutter
Muhammad Uzair
Muhammad Uzair

Posted on Originally published at uzairxdev.online

Build Prayer Times in Flutter

When I built Bayaan, an Islamic lifestyle app with prayer times, Adhan notifications, daily reminders and prophetic routines, the prayer times screen became the screen users opened every day. Bayaan runs on iOS and Android, is built with Flutter and Dart, and pairs Firebase and REST APIs with local notifications — but the prayer times themselves never touch a server. You can see the finished app in the Bayaan case study.

This guide shows how to build the same feature in your own Flutter app: calculate the five daily prayer times on-device, let the user pick the calculation method their community follows, show a live countdown to the next prayer, and schedule Adhan notifications that fire on time.

What are prayer times and how are they calculated?

Prayer times are defined by the position of the sun, not by a timetable you download. Fajr begins at dawn, when the sun is a set number of degrees below the horizon; Dhuhr begins just after the sun passes its highest point; Asr begins when the shadow of an object reaches a set length; Maghrib begins at sunset; and Isha begins when the twilight has faded. Because every one of those moments is a solar event, the times can be computed from three inputs — latitude, longitude and date — using high-precision astronomical equations. The adhan package is a pure Dart library that does exactly this, with no dependencies and no network calls, and its equations come from the book Astronomical Algorithms by Jean Meeus. That makes prayer times a perfect offline feature: the app works in airplane mode, in a basement masjid with no signal, and on a phone that has never had an account.

How do you calculate prayer times with the adhan package?

You calculate prayer times with the adhan package by giving it three things: where the user is, what day it is, and which calculation method to use. Coordinates takes latitude first and longitude second, and the calculation parameters come from a named method instead of being built by hand. The PrayerTimes object then holds Fajr, Sunrise, Dhuhr, Asr, Maghrib and Isha as DateTime values, plus sunset and the wraparound helpers ishaBefore and fajrAfter. Pass the device UTC offset so the returned times are local wall-clock times, and use PrayerTimes.today as a shortcut when you only need the current day. The madhab setting matters too: it changes the Asr shadow length, with Hanafi Asr later than Shafi Asr, so expose it in settings alongside the method.

import 'package:adhan/adhan.dart';

PrayerTimes todaysPrayerTimes({
  required double latitude,
  required double longitude,
  required Duration utcOffset,
}) {
  final coordinates = Coordinates(latitude, longitude);
  final params = CalculationMethod.karachi.getParameters();
  params.madhab = Madhab.shafi;

  return PrayerTimes(
    coordinates,
    DateComponents.from(DateTime.now()),
    params,
    utcOffset: utcOffset,
  );
}
Enter fullscreen mode Exit fullscreen mode

One detail trips up almost every first implementation: the DateComponents must be the local calendar date, not a UTC date, or the times land a day out near midnight. Build it from DateTime.now() in local time and you are safe. If a user reports times that are exactly an hour off, the cause is almost always the UTC offset — daylight saving changed and the stored offset did not — so read the offset fresh from the device instead of caching it.

Which calculation method should you use?

There is no single correct calculation method, and that is the most important product decision in a prayer times app. Each method is a preset of Fajr and Isha angles and minute adjustments published by a religious authority, and different communities follow different ones. The table below lists the common presets from the adhan package documentation — use it to offer the choice, not to pick for the user.

Method Fajr angle Isha angle Commonly used in
Muslim World League 18 degrees 17 degrees Europe, Far East
University of Islamic Sciences, Karachi 18 degrees 18 degrees Pakistan, Bangladesh, Afghanistan
Islamic Society of North America 15 degrees 15 degrees North America
Umm al-Qura University, Makkah 18.5 degrees 90 minutes after Maghrib Arabian Peninsula
Egyptian General Authority of Survey 19.5 degrees 17.5 degrees Africa, Middle East
Singapore 20 degrees 18 degrees Singapore, Malaysia, Indonesia

Never hardcode one method for every user: a Karachi-method Fajr in a North American city can be half an hour earlier than what the local masjid announces, and users notice immediately. Default to the method for the user's country when you can detect it, show the method name in settings, and add a per-prayer minute adjustment for users whose masjid adds a few minutes of caution to the printed time. The adhan package exposes adjustments as a map keyed by prayer, so a plus-two-minutes Fajr adjustment is one line. If you are building a companion feature, the Qibla finder guide covers the compass side of the same app, including the sensor handling that prayer times do not need.

How do you find the next prayer and show a countdown?

Finding the next prayer is a small search over the six times in the PrayerTimes object: take the first prayer whose time is still in the future, and if none is left today, the next prayer is tomorrow's Fajr. That wraparound case is the one to get right — after Isha the countdown must point at Fajr, not show a negative number or a blank screen. Build the ordered list of name-and-time pairs, use firstWhere with an orElse that falls back to tomorrow's Fajr, and drive the countdown text with a Timer that ticks once a second. Format the remaining time as hours, minutes and seconds, and show the prayer name next to it so the screen reads as one sentence: Fajr in 2 hours 14 minutes. Keep the timer cheap by rebuilding only the countdown widget, not the whole screen, and cancel it when the widget disposes.

({String name, DateTime time}) nextPrayer(PrayerTimes today, PrayerTimes tomorrow) {
  final prayers = <({String name, DateTime time})>[
    (name: 'Fajr', time: today.fajr),
    (name: 'Sunrise', time: today.sunrise),
    (name: 'Dhuhr', time: today.dhuhr),
    (name: 'Asr', time: today.asr),
    (name: 'Maghrib', time: today.maghrib),
    (name: 'Isha', time: today.isha),
  ];

  final now = DateTime.now();
  for (final prayer in prayers) {
    if (prayer.time.isAfter(now)) return prayer;
  }
  return (name: 'Fajr', time: tomorrow.fajr);
}
Enter fullscreen mode Exit fullscreen mode

Recompute the list whenever the day changes, because a countdown that crosses midnight must switch to the new day's times. A simple way to do this is to check the date inside the same one-second timer and rebuild the PrayerTimes objects when the day rolls over.

How do you schedule Adhan notifications that actually fire?

A prayer reminder that arrives late is worse than no reminder, so schedule Adhan notifications with zonedSchedule from flutter_local_notifications and the timezone package, not with a plain delayed notification. A zoned schedule is anchored to the device timezone, so it fires at the right wall-clock time even when the user crosses a timezone boundary or daylight saving starts. Schedule all five prayers each morning, or whenever the method, location or adjustments change, and use a distinct notification id per prayer so rescheduling one never cancels the others. On Android 12 and later, exact alarms need the SCHEDULE_EXACT_ALARM permission: request it with requestExactAlarmsPermission and fall back to an inexact schedule when the user declines, instead of crashing or silently scheduling nothing. Android also kills exact alarms on reboot, so re-schedule from a boot receiver or, more simply, re-schedule every time the app opens and once a day from a background task. The local notifications guide covers the plugin setup in detail, and the exact alarm guide covers the Android permission flow and the Android 12 changes.

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;

Future<void> scheduleAdhan({
  required FlutterLocalNotificationsPlugin plugin,
  required int id,
  required String prayerName,
  required DateTime time,
}) async {
  await plugin.zonedSchedule(
    id,
    'Time for $prayerName',
    'It is time for $prayerName prayer.',
    tz.TZDateTime.from(time, tz.local),
    const NotificationDetails(
      android: AndroidNotificationDetails(
        'adhan_channel',
        'Adhan Reminders',
        importance: Importance.max,
        priority: Priority.high,
      ),
    ),
    androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
    uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime,
  );
}
Enter fullscreen mode Exit fullscreen mode

Call tz.initializeTimeZones() once at startup and set the local location before scheduling anything, or tz.local silently stays on UTC and every notification fires hours off. For the Adhan audio itself, attach a custom sound to the notification channel on Android, or play the audio from the app when the user opens the reminder. In Bayaan the Adhan can also be cast to smart home devices from the notification.

How do you handle high latitudes and daylight saving?

High latitudes are where fixed-angle methods break down. Above roughly 48 degrees north or south, the sun stops reaching 18 degrees below the horizon in summer, so under an 18-degree method Fajr and Isha simply have no observable time on those days. The adhan package does not invent a time in that case, and your app must not either: set a high-latitude rule on the calculation parameters, such as middle of the night or seventh of the night, which divides the night between sunset and sunrise and derives Fajr and Isha from that span. Offer the rule in settings and note on screen when it is active, so the user knows the time is derived rather than observed. Daylight saving is the other seasonal trap: a prayer time is a wall-clock time, so when the clocks change, the UTC offset changes with them. Read the offset from the device at calculation time, never store it in the database, and recompute the day's times when the timezone changes. The same rule applies to travel: when the location changes by more than a few kilometres, recompute from the new coordinates, because a prayer time calculated for Karachi is wrong in Lahore by several minutes.

How do you keep prayer times accurate and offline?

Keep prayer times accurate by treating the calculation as the source of truth and the network as unnecessary. Compute on-device with the adhan package, cache only the current day's results in local storage so the screen renders instantly on launch, and recompute on every app start in case the date, location, method or adjustments changed while the app was closed. Get the location with the geolocator package and a clear permission prompt that explains why the app needs it, and always offer a city search as a fallback for users who decline location access — a saved latitude and longitude for their city is just as accurate for prayer times as live GPS. Test against a real timetable before you ship: pick your own city, compare each prayer against the local masjid's printed times for a week, and tune the per-prayer adjustments until they match. That weekly comparison is the cheapest QA a prayer app can do, and it catches method, madhab and offset mistakes that unit tests never will.

What did building Bayaan teach me?

Building Bayaan taught me that a prayer times app is a trust product before it is a technical one. Bayaan pairs prayer times with Adhan notifications, daily reminders and prophetic routines, and the features users rely on most are the quiet ones: the right method for their community, a notification that fires on time, and a screen that works with no account and no network. The app is built with Flutter and Dart, uses Firebase and REST APIs on the backend, and leans on local notifications for the Adhan. If you build one, ship the method picker on day one, test against your local masjid timetable for a week, and never let a silent failure eat a notification. Get those three right and the rest of the app is polish.

Get in touch and let's talk about your project.


Originally published at uzairxdev.online

Top comments (0)