DEV Community

Cover image for Build a Daily Dua + Hijri Month Widget in Flutter with Sample JSON
SunnahSource
SunnahSource

Posted on

Build a Daily Dua + Hijri Month Widget in Flutter with Sample JSON

Most Muslim apps have the same small "daily" card on their home screen: a dua of the day and some Hijri calendar info. In this tutorial we'll build that card in Flutter. It's about 150 lines of Dart and uses two small public sample files from SunnahSource, a set of Islamic JSON APIs for Quran, Hadith, Duas, Hijri calendar and more.

By the end you will have:

  • Dart models for the Duas and Hijri Calendar sample responses
  • A "Dua of the Day" that picks the same dua for everyone on a given day and changes at midnight
  • A language switcher that uses the translation keys in the JSON
  • A simple offline cache, so the card still shows when the device has no network

My earlier post gave a high-level overview of the Quran, Hadith and Prayer Times APIs. This one builds a single finished widget, start to finish.

1. Look at the data first

Both sample files are public and need no key:

GET https://sunnahsource.org/data/json/duas.json
GET https://sunnahsource.org/data/json/hijri-calendar.json
Enter fullscreen mode Exit fullscreen mode

Run curl on them before writing any code, because the shape of the JSON decides what your models look like.

duas.json (shortened; one item shown, translations trimmed):

{
  "title": "Islamic Duas",
  "description": "Essential duas with Arabic text and translations",
  "is_free": false,
  "items": [
    {
      "id": 2,
      "category": "Before Eating",
      "arabic": "بِسْمِ اللَّهِ",
      "transliteration": "Bismillah",
      "translations": {
        "en": "In the name of Allah.",
        "ur": "اللہ کے نام سے۔",
        "fr": "Au nom d'Allah."
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Things to notice:

  • translations is a map keyed by language code (en, ur, fr, de, tr, ms, ru, zh-CN, ja in the sample). Don't hard-code a fixed set of fields. Read the keys at runtime.
  • reference (for example "Quran 2:201") is present on some items only. Treat it as optional.

hijri-calendar.json (shortened):

{
  "title": "Hijri Calendar",
  "description": "Islamic calendar months, events and important dates",
  "is_free": false,
  "current_hijri": "1447 AH",
  "months": [
    {
      "number": 1,
      "name_ar": "مُحَرَّم",
      "name_en": "Muharram",
      "days": 30,
      "translations": { "en": "Sacred month — Islamic New Year, Ashura" }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

The sample contains a subset of months (it's a preview file), and current_hijri is a plain string. Your UI should cope with missing months instead of assuming all 12 are there. Full data and production endpoints come with an API key (see the end of the post).

2. Project setup

flutter create daily_card
cd daily_card
flutter pub add http shared_preferences
Enter fullscreen mode Exit fullscreen mode

3. Models

Create lib/models.dart:

class Dua {
  final int id;
  final String category;
  final String arabic;
  final String transliteration;
  final String? reference;
  final Map<String, String> translations;

  Dua.fromJson(Map<String, dynamic> j)
      : id = j['id'] as int,
        category = (j['category'] ?? '') as String,
        arabic = (j['arabic'] ?? '') as String,
        transliteration = (j['transliteration'] ?? '') as String,
        reference = j['reference'] as String?,
        translations = Map<String, String>.from(j['translations'] ?? {});

  String translation(String lang) =>
      translations[lang] ?? translations['en'] ?? '';
}

class HijriMonth {
  final int number;
  final String nameAr;
  final String nameEn;
  final int days;
  final Map<String, String> translations;

  HijriMonth.fromJson(Map<String, dynamic> j)
      : number = j['number'] as int,
        nameAr = (j['name_ar'] ?? '') as String,
        nameEn = (j['name_en'] ?? '') as String,
        days = (j['days'] ?? 0) as int,
        translations = Map<String, String>.from(j['translations'] ?? {});
}

class HijriCalendar {
  final String currentHijri;
  final List<HijriMonth> months;

  HijriCalendar.fromJson(Map<String, dynamic> j)
      : currentHijri = (j['current_hijri'] ?? '') as String,
        months = ((j['months'] ?? []) as List)
            .map((m) => HijriMonth.fromJson(m as Map<String, dynamic>))
            .toList();
}
Enter fullscreen mode Exit fullscreen mode

4. A small client with an offline cache

Create lib/sunnah_client.dart. It tries the network first. If that fails, it falls back to the last good response saved in shared_preferences.

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'models.dart';

class SunnahClient {
  static const _base = 'https://sunnahsource.org/data/json';

  Future<Map<String, dynamic>> _getJson(String slug) async {
    final prefs = await SharedPreferences.getInstance();
    final cacheKey = 'ss_$slug';
    try {
      final res = await http
          .get(Uri.parse('$_base/$slug.json'))
          .timeout(const Duration(seconds: 10));
      if (res.statusCode == 200) {
        final body = utf8.decode(res.bodyBytes); // keep Arabic/Urdu intact
        await prefs.setString(cacheKey, body);
        return jsonDecode(body) as Map<String, dynamic>;
      }
    } catch (_) {
      // fall through to cache
    }
    final cached = prefs.getString(cacheKey);
    if (cached != null) return jsonDecode(cached) as Map<String, dynamic>;
    throw Exception('No data for $slug (offline and no cache)');
  }

  Future<List<Dua>> duas() async {
    final j = await _getJson('duas');
    return ((j['items'] ?? []) as List)
        .map((e) => Dua.fromJson(e as Map<String, dynamic>))
        .toList();
  }

  Future<HijriCalendar> hijri() async =>
      HijriCalendar.fromJson(await _getJson('hijri-calendar'));
}
Enter fullscreen mode Exit fullscreen mode

Note the utf8.decode(res.bodyBytes). If you use res.body and the server's charset header ever goes missing, Arabic text can come out garbled. Decoding the bytes yourself avoids that.

5. "Dua of the Day" that's stable all day

We want everyone to see the same dua on the same day, without any server logic. Use the day number since the Unix epoch, modulo the list length:

Dua duaOfTheDay(List<Dua> duas, [DateTime? now]) {
  final d = (now ?? DateTime.now()).toUtc();
  final dayIndex = DateTime.utc(d.year, d.month, d.day)
          .millisecondsSinceEpoch ~/
      Duration.millisecondsPerDay;
  return duas[dayIndex % duas.length];
}
Enter fullscreen mode Exit fullscreen mode

6. The widget

lib/main.dart:

import 'package:flutter/material.dart';
import 'models.dart';
import 'sunnah_client.dart';

void main() => runApp(const MaterialApp(home: DailyCardPage()));

class DailyCardPage extends StatefulWidget {
  const DailyCardPage({super.key});
  @override
  State<DailyCardPage> createState() => _DailyCardPageState();
}

class _DailyCardPageState extends State<DailyCardPage> {
  final _client = SunnahClient();
  late Future<(List<Dua>, HijriCalendar)> _data;
  String _lang = 'en';

  @override
  void initState() {
    super.initState();
    _data = _load();
  }

  Future<(List<Dua>, HijriCalendar)> _load() async =>
      (await _client.duas(), await _client.hijri());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Daily Card')),
      body: FutureBuilder(
        future: _data,
        builder: (context, snap) {
          if (snap.connectionState != ConnectionState.done) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snap.hasError) {
            return Center(child: Text('Could not load: ${snap.error}'));
          }
          final (duas, cal) = snap.data!;
          if (duas.isEmpty) return const Center(child: Text('No duas'));
          final dua = duaOfTheDay(duas);
          final langs = dua.translations.keys.toList()..sort();

          return ListView(
            padding: const EdgeInsets.all(16),
            children: [
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Text(dua.category,
                          style: Theme.of(context).textTheme.labelLarge),
                      const SizedBox(height: 12),
                      Text(dua.arabic,
                          textDirection: TextDirection.rtl,
                          textAlign: TextAlign.right,
                          style: const TextStyle(fontSize: 26, height: 1.8)),
                      const SizedBox(height: 8),
                      Text(dua.transliteration,
                          style: const TextStyle(fontStyle: FontStyle.italic)),
                      const SizedBox(height: 8),
                      Text(dua.translation(_lang),
                          textDirection: _lang == 'ur'
                              ? TextDirection.rtl
                              : TextDirection.ltr),
                      if (dua.reference != null) ...[
                        const SizedBox(height: 8),
                        Text(dua.reference!,
                            style: Theme.of(context).textTheme.bodySmall),
                      ],
                      const SizedBox(height: 12),
                      DropdownButton<String>(
                        value: langs.contains(_lang) ? _lang : langs.first,
                        items: [
                          for (final l in langs)
                            DropdownMenuItem(value: l, child: Text(l))
                        ],
                        onChanged: (v) => setState(() => _lang = v!),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),
              Text('Hijri year: ${cal.currentHijri}',
                  style: Theme.of(context).textTheme.titleMedium),
              const SizedBox(height: 8),
              for (final m in cal.months)
                ListTile(
                  leading: CircleAvatar(child: Text('${m.number}')),
                  title: Text('${m.nameEn}  ·  ${m.nameAr}'),
                  subtitle: Text(
                      '${m.days} days — ${m.translations[_lang] ?? m.translations['en'] ?? ''}'),
                ),
            ],
          );
        },
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

(Records like (List<Dua>, HijriCalendar) need Dart 3, which ships with any current Flutter SDK.)

Run it with flutter run. You get a dua card with a working language switcher, and below it the Hijri months from the sample. Turn on airplane mode and restart the app: the card still loads from the cache.

7. Notes for Flutter Web and plain JavaScript

On Android and iOS, the code above works as-is. In a browser (Flutter Web, or a plain fetch() from another domain), the sample files currently don't send CORS headers. That means a cross-origin fetch will be blocked. You have two options:

  • Call the JSON from your own backend (or a serverless function) and send it to your frontend, or
  • Bundle a copy of the sample in your assets while you prototype.

Doing this from the server is a good idea anyway, because your production API key should never go to the browser.

The same "dua of the day" logic in JavaScript (Node 18+):

const res = await fetch('https://sunnahsource.org/data/json/duas.json');
const { items } = await res.json();
const day = Math.floor(Date.now() / 86_400_000);
const dua = items[day % items.length];
console.log(dua.category, '|', dua.transliteration, '|', dua.translations.en);
Enter fullscreen mode Exit fullscreen mode

8. Going to production

The /data/json/*.json files are preview samples: a few items, so you can design your UI. For the full dataset:

  1. Open the API page, for example the Duas API or the Hijri Calendar API.
  2. Fill in the Apply form with your project details.
  3. After your application is approved, your production endpoint and personal API key are sent to you by email.

Keep the key on your server, and keep the offline cache. Your users will be glad when the card loads instantly.

If you're building a full prayer app, the Prayer Times API pairs well with the Hijri card. If you'd rather have the whole app built for you, SunnahSource also does custom Islamic app development.


What would you add next: a home-screen widget (home_widget package), or push reminders for the start of each Hijri month? Let me know in the comments.

Top comments (0)