PakDataKit for Dart and Flutter
Utilities for Pakistani data: CNIC, mobile numbers and networks, WhatsApp links, IBAN and banks, postal codes, cities and districts, address parsing, Roman Urdu, Urdu slugs and alphabetical sorting, Hijri dates, public holidays, rupee formatting, amounts in words, NTN/STRN, sales tax, income tax on salary, landlines, electricity and gas bill numbers, Raast QR codes, and form-field helpers that format as the user types.
This is the Dart port of the pakdatakit npm package.
It ships the same datasets and is tested against the same 32,000+ test
vectors generated from the TypeScript library (also used by the Python
port), so all three give identical results.
- Pure Dart, no dependencies
- Works on every platform: Flutter (Android, iOS, web, desktop), the Dart
VM and server, and Dart compiled to JavaScript. No
dart:io; the data is embedded in the package. - Null-safe, immutable result classes with value equality and
toJson()
Install
dart pub add pakdatakit
# or, in a Flutter app
flutter pub add pakdatakit
Examples
import 'package:pakdatakit/pakdatakit.dart';
validateCNIC('35202-1234567-1'); // true
getCNICInfo('35202-1234567-1');
// CNICInfo{digits: 3520212345671, formatted: 35202-1234567-1, province: Punjab, gender: male}
formatPhone('0300 1234567'); // '+923001234567'
getNetwork('0345-1234567'); // NetworkName.telenor
createWhatsAppLink('03001234567', 'Salam!'); // 'https://wa.me/923001234567?text=Salam!'
validateIBAN('PK36 SCBL 0000 0011 2345 6702'); // true
getBankFromIBAN('PK36SCBL0000001123456702'); // 'Standard Chartered Bank (Pakistan) Limited'
getBankInfo('MEZN')?.type; // BankType.islamic
getProvince('Lahore'); // 'Punjab'
getDivisions('Sindh'); // ['Hyderabad', 'Karachi', 'Larkana', ...]
getDivisionOfDistrict('Lahore'); // 'Lahore'
getTehsils('Rawalpindi'); // tehsils of the district, sorted
getTehsilDistrict('Murree'); // 'Rawalpindi'
parseAddress('House 12, Street 5, Model Town Lahore 54000').postalCode; // '54000'
getPostOffice('48330')?.office; // 'Dulmial'
searchPostOffices('Dulmial').length; // offices whose name or town matches
scoreAddress('12 Model Town Lahore').score; // 60 (no street, postal code or landmark)
phoneRiskSignals('0300 0000000'); // [PhoneRiskFlag.repeatedDigits]
formatPKR(150000); // 'Rs. 150,000'
formatLakh(2500000); // '25 Lakh'
amountInWords(125000, cheque: true); // 'Rupees One Lakh Twenty-Five Thousand Only'
numberToWords(125000, language: WordsLanguage.ur); // 'ایک لاکھ پچیس ہزار'
formatHijri(DateTime(2026, 3, 3)); // '14 Ramadan 1447'
isPakistanHoliday(DateTime(2025, 8, 14)); // true
getPakistanHolidays(2026).first; // Holiday{id: kashmir-day, ...}
final payload = createRaastP2PQr(
iban: 'PK36SCBL0000001123456702',
amount: 1500,
expiresIn: '1d', // or const Duration(days: 1)
);
validateRaastQr(payload).valid; // true
getSalesTaxRate(kind: SalesTaxKind.goods)?.rate; // 18 (today)
calculateSalesTax(1000, rate: 18)?.gross; // 1180
splitInclusive(99.99, 18)?.net; // 84.74
calculateSalaryTax(1800000, taxYear: 2026)?.tax; // 72000
calculateMonthlySalaryTax(150000, taxYear: 2026)?.monthly; // 6000
slugify('Lahore Fort, 2024'); // 'lahore-fort-2024'
['ے', 'بھائی', 'آم', 'باغ', 'اب']..sort(compareUrdu); // ['اب', 'آم', 'باغ', 'بھائی', 'ے']
isRTL('123 سلام'); // true
parseElectricityRef('02-12624-0045901 R')?.formatted; // '02 12624 0045901 R'
parseElectricityRef('0400012345678')?.disco; // 'K-Electric'
validateGasConsumerNumber('12345678901', 'SNGPL'); // true
formatCNICInput('3520212'); // '35202-12'
checkPhoneInput('0300 12'); // InputState.incomplete
Each module can also be imported on its own, mirroring the npm entry points:
import 'package:pakdatakit/cnic.dart';
import 'package:pakdatakit/raast.dart';
Available: address, bills, cnic, format, geo, hijri, holidays, iban,
incometax, input, networks, numbers, phone, postal, quality, raast,
salestax, tax, text, whatsapp and words.
API
Every function of the npm package is available under the same name
(validateCNIC, createRaastP2PQr, …). See the
API reference for what each one does.
In Dart:
- Options objects are named parameters:
{ expiresIn: '1d' }→expiresIn: '1d',{ language: 'ur' }→language: WordsLanguage.ur. - Results are immutable classes with
constconstructors,==/hashCode,toString()andtoJson(), which gives the same JSON (keys and values) as the npm package. - Closed sets of strings are enums (
InputState,NetworkName,NumberType,BankType,NTNType,HolidayId,RaastQrError, …), each with a.valueholding the npm string, e.g.NumberType.tollFree.value == 'toll-free'. nullwhere the npm package returnsnull.- Divisions and tehsils (
getDivisions,getDivisionOfDistrict,getTehsils,getTehsilDistrict) use the 2023 census: each tehsil is recorded under the district it was in then, and districts created since the census have no division.getDivisionsandgetTehsilDistricttake the province as an optional positional argument. - Postal codes:
getCityByPostalCodeand the other postal-code lookups only know the offices of cities pakdatakit lists (457 codes), so a village code returnsnull.getPostOfficeandsearchPostOfficescover every delivery office in Pakistan Post's directory (about 2,560) and returnPostOfficevalues (code,office,town,district,province). The directory is only referenced by these two functions, so release builds that do not call them leave it out. BankTypehas the State Bank's groups, includingBankType.publicSector('public-sector') for public sector commercial banks such as National Bank of Pakistan;BankInfo.activeisfalsefor banks that merged into another or have closed.- Delivery quality:
scoreAddressreturns anAddressScore(score0-100, themissingAddressParts in the order ofaddressWeights, andparsed, theparseAddressresult plus any postal-code/province warning).phoneRiskSignalsreturns a list ofPhoneRiskFlags (invalid,landline,notMobile,repeatedDigits,sequentialDigits,testNumber;.valueholds the npm string, e.g.'repeated-digits'), or[]for an unremarkable mobile number. Both are heuristics and never throw.ADDRESS_WEIGHTSisaddressWeights, aMap<AddressPart, int>. - Sales tax:
getSalesTaxRate(kind: SalesTaxKind.goods, province: …, date: …)returns aSalesTaxRate(kind,authority,province,rate,from,to,law,source) ornull;calculateSalesTax(amount, rate: …, province: …, kind: …, date: …, inclusive: …)andsplitInclusive(gross, rate)returnSalesTaxAmounts(net,tax,gross,rate, alldoubles) ornull. The npmSalesTaxRateQueryandSalesTaxOptionsobjects are these named parameters;dateis a'YYYY-MM-DD'string or aDateTimeand defaults to today. Amounts are rounded half up to the paisa from the number as written (1.005is Rs 1.01), computed exactly withBigInton every platform. They never throw. - Income tax on salary:
calculateSalaryTax(annualIncome, taxYear: …, date: …)andcalculateMonthlySalaryTax(monthlySalary, taxYear: …, date: …)return aSalaryTax(tax,monthly,effectiveRate, alldoubles;slab, aSalaryTaxSlabwithover,upTo,fixedandrate;taxYear) ornull, from the salaried rate table of the Income Tax Ordinance 2001 (First Schedule, Part I, Division I, clause (2)) for tax years 2020 to 2027. The npmSalaryTaxOptionsobject is these named parameters:taxYear(anint) takes precedence overdate(a'YYYY-MM-DD'string or aDateTime), and with neither the current tax year is used.getSalaryTaxSlabs([taxYear])returns theSalaryTaxYear(taxYear,from,to,law,source,slabs, an unmodifiable list),getSalaryTaxYears()the years covered andgetTaxYear([date])the tax year (July to June, named after the June it ends in) of a date. Tax is rounded half up to the paisa, exactly withBigInton every platform. Only the rate table is applied: the surcharge, tax credits, exemptions, the pension rate and withholding adjustments are not. They never throw. Also aspackage:pakdatakit/incometax.dart. - Urdu text:
slugify(input, script: SlugScript.any)makes a URL slug, keeping Urdu letters as they are (SlugScript.latinkeeps onlya-z,SlugScript.urduonly Urdu letters; digits become0-9).compareUrdu(a, b)sorts in the CLDR Urdu alphabetical order (بھ, پھ, … are letters of their own), the same on every platform without ICU, and can be passed straight toList.sort.isRTL(text)istruewhen the first letter is from a right-to-left script, andwrapBidi(text, [direction])wraps text in Unicode directional isolates (BidiDirection.auto, the default,rtlorltr). They never throw. - Utility bills:
parseElectricityRef(input)returns anElectricityRef(type, anElectricityRefType:reference,customerId('customer-id') orkElectric('k-electric');digits;formatted, e.g.'02 12624 0045901 R';urbanRural,'U','R'ornull;disco,'K-Electric'ornull) ornull;validateElectricityRef(input)istruewhen it parses.validateGasConsumerNumber(input, company)takes the company as a string,'SNGPL'(11 digits) or'SSGC'(10 digits) in any case, e.g.GasCompany.sngpl.value; any other company givesfalse. Spaces, dashes, dots and Urdu digits are accepted. Only the format is checked. They never throw. - Couriers (experimental):
mapCourierStatusandCourierStatusmay change in a minor release while more couriers' status lists are added (see CONTRIBUTING.md).mapCourierStatus(courier, raw)maps a courier's own status (name, numeric ID or code) to aCourierStatus(pending,booked,pickedUp,inTransit,outForDelivery,attempted,underReview,delivered,returning,returned,cancelled;.valueholds the npm string, e.g.'out-for-delivery') ornull.courieris a string such as'PostEx','LCS'orCourier.mAndP.value(any case);rawis aStringor a non-negative whole number (5and5.0both match'5'). Only documented statuses are mapped (PostEx's merchant API guide and Leopards' "Returned to Shipper"), so TCS, M&P, Trax and BlueEx givenull.normalizeCityForCourier(input)maps'LHR','Khi','Pindi','Lyallpur','Karachi City'or'لاہور'to the city list's name, ornull. No API is called, and they never throw. - FBR Digital Invoicing: the invoice is the JSON posted to FBR, a
Map<String, Object?>with the spec's camelCase keys (FbrInvoice,FbrInvoiceItem,FbrInvoiceInputandFbrInvoiceItemInputare typedefs for it).buildFbrInvoice(input)works out each line'ssalesTaxApplicablewhen it is left out (N%of the value excluding tax, or of the retail price for Third Schedule goods, withcalculateSalesTax;Rs.Nper unit; 0 otherwise), fills FBR's defaults and returns anFbrInvoiceBuild(invoice, andtotals, anFbrInvoiceTotalsofdoubles for your records), ornullifinputis not a map with anitemslist of maps.validateFbrInvoice(invoice, today: 'YYYY-MM-DD')takes any value (e.g. fromjsonDecode) and returns anFbrInvoiceValidation(valid, anderrors, a list ofFbrInvoiceErrorwith FBR'scodeornull, thefield, e.g.'items[0].rate', and amessage), in the order the npm package reports them;today(the npmFbrInvoiceValidationOptions) also rejects future dates (0043).expectedSalesTax(item)gives the tax FBR expects on a line, ornull.FbrInvoiceTypeandFbrRegistrationTypehold the allowed strings (FbrInvoiceType.saleInvoice.value == 'Sale Invoice'), andfbrDiSpecVersionisFBR_DI_SPEC_VERSION('1.12', PRAL's DI API specification). There is no HTTP client and no token handling; values only FBR's reference APIs can confirm (provinces, HS codes, units, rates, sale types, SROs) are checked for presence only. They never throw. Also aspackage:pakdatakit/fbr_invoice.dart. - An
ArgumentErrorwhere the npm package throws aRangeError, e.g.formatPKR(double.nan)or a Raast QR with an amount but no expiry. - Dates are local
DateTimes; only the calendar date (or, for Raast expiry, the local time) is used.getHolidaysOnandisPakistanHolidaytake aDateTimeor a'YYYY-MM-DD'string. - Whole-number options are
int(Hijrioffset,hijriOffset, years); amounts arenum. ParsedRaastQr.isDynamicandcreateMerchantQr(isDynamic: …)are calleddynamicin the npm package (dynamicis a built-in Dart type);toJson()still usesdynamic.createRaastP2PQrtakes an optionalnow(the timeexpiresIncounts from), andexpiresInalso accepts aDuration.
dataVersion gives the date the datasets were last checked against their
sources; see DATA.md
for where each dataset comes from.
Same results as the npm package
The datasets in lib/src/data/ are generated from the repository's shared
data/*.json, and the package is tested against the shared
test-vectors/,
produced by running the TypeScript library over 32,000 inputs. The tests pass
both on the Dart VM and compiled to JavaScript.
JavaScript behaviours that differ in Dart are reproduced exactly: whitespace
and trim, full Unicode case mapping (ß → SS), NFC normalization,
Math.round, number-to-string conversion, toFixed, localeCompare
ordering and stable sorting.
Development
From dart/:
dart pub get
dart test
The files in lib/src/data/ are generated; don't edit them by hand. From the
repository root:
node scripts/generate-dart-data.mjs
License
MIT
Libraries
- address
- Free-form Pakistani address parsing and formatting.
- bills
- Electricity bill reference numbers, customer IDs and K-Electric account numbers, and gas consumer numbers.
- cnic
- CNIC (Computerized National Identity Card) validation and decoding.
- courier
- Courier helpers: courier statuses in one vocabulary, and city names as couriers and customers write them. No courier API is called.
- fbr_invoice
- FBR Digital Invoicing: a builder that works out the sales tax and an offline validator for the invoice JSON posted to FBR's Digital Invoicing API. No HTTP client and no token handling.
- format
- Pakistani Rupee and lakh/crore formatting.
- geo
- Cities, districts and provinces.
- hijri
- Hijri (Islamic) calendar conversion.
- holidays
- Pakistani federal public holidays.
- iban
- Pakistani IBAN validation and bank lookup.
- incometax
- Income tax on salary, from the salaried rate table for each tax year.
- input
- Formatting and checking CNIC, phone and IBAN form fields as the user types.
- networks
- Mobile network detection from the 03XX prefix.
- numbers
- Landline, UAN, toll-free, premium and personal numbers.
- pakdatakit
- Utilities for Pakistani data: CNIC, phone, IBAN, postal codes, address parsing, Hijri dates, holidays, amounts in words, Raast QR codes, sales tax, income tax on salary, FBR digital invoices, passport and vehicle registration number formats, utility bill numbers, courier statuses and city names, and Urdu slugs, sorting and bidirectional text.
- passport
- Pakistani passport number checks.
- phone
- Pakistani mobile number validation, formatting and analysis.
- postal
- Pakistani postal code lookups.
- quality
- Delivery-address completeness scores and phone-number risk signals.
- raast
- Raast QR codes: person-to-person and merchant payloads, parsing and validation.
- salestax
- Standard sales tax rates on goods and services, and sales tax amounts.
- tax
- National Tax Number (NTN) and Sales Tax Registration Number (STRN) checks.
- text
- Text normalization, Roman Urdu spelling, Urdu digits, slugs, Urdu alphabetical order and bidirectional text.
- vehicle
- Pakistani vehicle registration number checks.
- WhatsApp click-to-chat links.
- words
- Numbers and rupee amounts in words (English and Urdu).