DEV Community

SunnahSource
SunnahSource

Posted on

Build a multilingual Tafseer (Quran commentary) viewer in Flutter from a JSON API

Many Muslim apps want to show a short tafseer (commentary) next to each ayah, and let the reader switch language. In this post we build a small Flutter screen that does exactly that, using the JSON shape of the Tafseer API from QuraniAPI.

The JSON shape

The Tafseer API returns Surah Al-Fatiha with ayah-by-ayah commentary in 9 languages (en, ur, fr, de, tr, ms, ru, zh-CN, ja). Trimmed down, the response looks like this (values shortened):

{
  "title": "Comprehensive Tafseer",
  "is_free": false,
  "surah": { "number": 1, "name": "Al-Fatiha", "arabic": "..." },
  "items": [
    {
      "ayah": 1,
      "arabic": "...",
      "translations": { "en": "...", "ur": "...", "fr": "...", "de": "..." }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Endpoint (needs an API key — see how to get access):

https://quranicapi.online/api/serve.php?slug=tafseer&lang=all
Enter fullscreen mode Exit fullscreen mode

The full endpoint reference is in the docs.

Dart models

class TafseerItem {
  final int ayah;
  final String arabic;
  final Map<String, String> translations;
  TafseerItem(this.ayah, this.arabic, this.translations);

  factory TafseerItem.fromJson(Map<String, dynamic> j) => TafseerItem(
        j['ayah'] as int,
        j['arabic'] as String? ?? '',
        (j['translations'] as Map<String, dynamic>? ?? {})
            .map((k, v) => MapEntry(k, v.toString())),
      );
}

class Tafseer {
  final String surahName;
  final String surahArabic;
  final List<TafseerItem> items;
  Tafseer(this.surahName, this.surahArabic, this.items);

  factory Tafseer.fromJson(Map<String, dynamic> j) => Tafseer(
        j['surah']['name'] as String,
        j['surah']['arabic'] as String,
        (j['items'] as List).map((e) => TafseerItem.fromJson(e)).toList(),
      );
}
Enter fullscreen mode Exit fullscreen mode

Fetching (with the http package)

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

Future<Tafseer> fetchTafseer() async {
  final uri = Uri.parse(
      'https://quranicapi.online/api/serve.php?slug=tafseer&lang=all');
  final res = await http.get(uri);
  if (res.statusCode != 200) {
    throw Exception('HTTP ${res.statusCode}');
  }
  return Tafseer.fromJson(jsonDecode(utf8.decode(res.bodyBytes)));
}
Enter fullscreen mode Exit fullscreen mode

Tafseer is a premium API, so you'll need a key — see the docs and the pricing page for how access works. The Quran Translations API is free and uses the same serve.php?slug=...&lang=...\ pattern, so you can prototype with it first.

Tip: always decode with utf8.decode(res.bodyBytes) so Arabic and Urdu text isn't garbled.

The screen: language chips + RTL-aware text

import 'package:flutter/material.dart';

const langs = ['en', 'ur', 'fr', 'de', 'tr', 'ms', 'ru', 'zh-CN', 'ja'];
const rtl = {'ur'};

class TafseerScreen extends StatefulWidget {
  final Tafseer data;
  const TafseerScreen({super.key, required this.data});
  @override
  State<TafseerScreen> createState() => _TafseerScreenState();
}

class _TafseerScreenState extends State<TafseerScreen> {
  String lang = 'en';

  @override
  Widget build(BuildContext context) {
    final d = widget.data;
    return Scaffold(
      appBar: AppBar(title: Text('${d.surahName} · ${d.surahArabic}')),
      body: Column(children: [
        SizedBox(
          height: 52,
          child: ListView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.all(8),
            children: [
              for (final l in langs)
                Padding(
                  padding: const EdgeInsets.only(right: 6),
                  child: ChoiceChip(
                    label: Text(l),
                    selected: lang == l,
                    onSelected: (_) => setState(() => lang = l),
                  ),
                ),
            ],
          ),
        ),
        Expanded(
          child: ListView.separated(
            padding: const EdgeInsets.all(16),
            itemCount: d.items.length,
            separatorBuilder: (_, __) => const Divider(height: 32),
            itemBuilder: (_, i) {
              final it = d.items[i];
              return Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Text('Ayah ${it.ayah}',
                      style: Theme.of(context).textTheme.labelLarge),
                  const SizedBox(height: 8),
                  Text(it.arabic,
                      textDirection: TextDirection.rtl,
                      style: const TextStyle(fontSize: 24, height: 1.8)),
                  const SizedBox(height: 8),
                  Text(
                    it.translations[lang] ?? '—',
                    textDirection: rtl.contains(lang)
                        ? TextDirection.rtl
                        : TextDirection.ltr,
                    style: const TextStyle(fontSize: 16, height: 1.6),
                  ),
                ],
              );
            },
          ),
        ),
      ]),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Offline-first idea

Commentary text rarely changes, so cache the raw JSON (e.g. with shared_preferences or a file in the app documents dir) after the first successful fetch and load it on the next launch before hitting the network.

Related APIs

If you're building a full Quran app, the same site also has a Quran Translations API, a Word-by-Word Quran API and a Hadith API. The full list is on the APIs page, and more examples live in our GitHub repo.

Questions or feature requests? Drop a comment below.

Top comments (0)