fajfield_reports_flutter 0.2.0
fajfield_reports_flutter: ^0.2.0 copied to clipboard
Flutter add-on for fajfield_reports. Draws report text with Flutter's engine so every language prints, shows reports on screen, and makes PDFs and page pictures.
// fajfield_reports_flutter example: render .fjt templates (made in the Fajfield report designer) with your
// app's data, show them on screen, then print or share the PDF. Everything runs on the device, offline.
import 'dart:convert';
import 'package:fajfield_reports_flutter/fajfield_reports_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:printing/printing.dart';
void main() => runApp(const ReportsDemo());
const brand = Color(0xFF0B7A45);
class ReportsDemo extends StatelessWidget {
const ReportsDemo({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Fajfield Reports',
debugShowCheckedModeBanner: false,
theme: ThemeData(colorSchemeSeed: brand, useMaterial3: true),
darkTheme: ThemeData(colorSchemeSeed: brand, useMaterial3: true, brightness: Brightness.dark),
home: const HomePage(),
);
}
/// A sample: a template from assets plus the data an app would pass.
class Sample {
const Sample(this.title, this.subtitle, this.asset, this.icon, this.data);
final String title, subtitle, asset;
final IconData icon;
final Map<String, dynamic> Function() data;
}
// ---- data an app would load from its database or API ----
Map<String, dynamic> invoiceData({int items = 6, bool malayalam = false}) {
const en = [('Coconut oil 1 L', 4.5), ('Basmati rice 5 kg', 18.0), ('Green tea 100 bags', 3.2), ('Olive oil 500 ml', 7.9), ('Whole wheat flour 2 kg', 2.4), ('Black pepper 200 g', 3.6), ('Cashew nuts 500 g', 9.5), ('Dark chocolate 100 g', 1.8)];
const ml = [('വെളിച്ചെണ്ണ 1 ലിറ്റർ', 4.5), ('ബസ്മതി അരി 5 കിലോ', 18.0), ('ചായപ്പൊടി 250 ഗ്രാം', 3.2), ('കുരുമുളക് 200 ഗ്രാം', 3.6), ('കശുവണ്ടി 500 ഗ്രാം', 9.5), ('ഗോതമ്പ് പൊടി 2 കിലോ', 2.4)];
final products = malayalam ? ml : en;
return {
'company': {'name': 'Harbour Foods Co.', 'address': '120 Harbour Road, Kochi 682016, India', 'email': 'billing@harbourfoods.example', 'taxId': 'Tax ID 32ABCDE1234F1Z5', 'web': 'harbourfoods.example'},
'customer': malayalam ? {'name': 'ഫ്രഷ് മാർട്ട് സൂപ്പർമാർക്കറ്റ്', 'address': 'എം.ജി. റോഡ്, കൊച്ചി 682016'} : {'name': 'Fresh Mart Supermarket', 'address': '14 Marine Drive\nDubai, United Arab Emirates'},
'invoice': {'no': 'INV-2026-${451 + items}', 'date': DateTime.now().toIso8601String(), 'due': DateTime.now().add(const Duration(days: 14)).toIso8601String(), 'terms': malayalam ? '14 ദിവസത്തിനകം പണം നൽകുക. നന്ദി!' : 'Payment due within 14 days. Thank you for your business.'},
'items': [
for (var i = 0; i < items; i++) {'name': products[i % products.length].$1 + (i >= products.length ? ' · ${i ~/ products.length + 1}' : ''), 'qty': 1 + (i * 7) % 9, 'rate': products[i % products.length].$2, 'taxRate': 0.05},
],
};
}
Map<String, dynamic> stockData() => {
'report': {'warehouse': 'Main warehouse', 'by': 'Inventory team'},
'items': [
for (var i = 0; i < 60; i++) {'sku': 'SKU-${1001 + i}', 'name': ['Coconut oil 1 L', 'Basmati rice 5 kg', 'Green tea', 'Olive oil', 'Wheat flour', 'Black pepper'][i % 6], 'location': ['A-01-1', 'A-02-1', 'B-01-3', 'C-02-1'][i % 4], 'qty': (i * 37) % 140, 'reorder': 20 + (i % 4) * 10},
],
};
Map<String, dynamic> salesData() {
const customers = ['Al Noor Trading', 'Fresh Mart Supermarket', 'Gulf Star Hypermarket', 'Harbour Cafe', 'Oasis Grocers'];
const products = [('Coconut oil 1 L', 12.0), ('Basmati rice 5 kg', 45.0), ('Green tea 100 bags', 8.0), ('Olive oil 500 ml', 19.5), ('Whole wheat flour 2 kg', 6.0)];
return {
'report': {'from': '2026-11-01', 'to': '2026-11-30', 'notes': 'Figures exclude VAT. Returns are shown as negative quantities and are subtracted from the customer subtotal. Customers are listed with the highest sales first.'},
'sales': [
for (var i = 0; i < 42; i++) {'customer': customers[(i * 3) % 5], 'invoice': 'INV-${2400 + i}', 'date': '2026-11-${(1 + (i * 7) % 29).toString().padLeft(2, '0')}', 'product': products[i % 5].$1, 'qty': i % 13 == 5 ? -2 : 2 + (i * 5) % 18, 'rate': products[i % 5].$2},
],
};
}
final samples = [
const Sample('Tax invoice', 'A4 · logo, table, totals, QR code', 'assets/invoice.fjt', Icons.receipt_long_rounded, invoiceData),
Sample('Malayalam invoice', 'Same template, data in Malayalam', 'assets/invoice.fjt', Icons.translate_rounded, () => invoiceData(malayalam: true)),
Sample('Long invoice', '48 lines · continues over pages', 'assets/invoice.fjt', Icons.library_books_rounded, () => invoiceData(items: 48)),
const Sample('Stock report', '60 items · repeated headers, page x of y', 'assets/stock.fjt', Icons.inventory_2_rounded, stockData),
const Sample('Sales by customer', 'Groups with subtotals, sorted by total', 'assets/sales.fjt', Icons.groups_rounded, salesData),
];
final renderer = FlutterReportRenderer();
final _templates = <String, FjReport>{};
Future<FjReport> loadTemplate(String asset) async => _templates[asset] ??= FjReport.fromJsonString(await rootBundle.loadString(asset));
// ---- home: a gallery of samples with live thumbnails ----
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme, tt = Theme.of(context).textTheme;
return Scaffold(
body: CustomScrollView(slivers: [
const SliverAppBar.large(title: Text('Fajfield Reports')),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Card(
color: cs.primaryContainer,
child: Padding(
padding: const EdgeInsets.all(18),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text('Design once, render anywhere', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700, color: cs.onPrimaryContainer)),
const SizedBox(height: 6),
Text('These templates were made in the Fajfield report designer and are drawn here by Flutter, on this device, with app data. Tap one to view, print or share it.', style: TextStyle(color: cs.onPrimaryContainer)),
]),
),
),
),
),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 260, mainAxisSpacing: 16, crossAxisSpacing: 16, childAspectRatio: 0.62),
delegate: SliverChildBuilderDelegate((context, i) => SampleCard(samples[i]), childCount: samples.length),
),
),
]),
);
}
}
class SampleCard extends StatefulWidget {
const SampleCard(this.sample, {super.key});
final Sample sample;
@override
State<SampleCard> createState() => _SampleCardState();
}
class _SampleCardState extends State<SampleCard> {
late final Future<FlutterLayout> layout = loadTemplate(widget.sample.asset).then((r) => renderer.layout(r, data: widget.sample.data()));
@override
Widget build(BuildContext context) {
final t = Theme.of(context);
return Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => ReportPage(widget.sample))),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Expanded(
child: Container(
color: t.colorScheme.surfaceContainerHighest,
padding: const EdgeInsets.all(14),
child: FutureBuilder(
future: layout,
builder: (_, s) {
if (s.hasError) return Center(child: Text('${s.error}', style: t.textTheme.bodySmall));
if (!s.hasData) return const Center(child: CircularProgressIndicator());
final l = s.data!;
return Center(child: AspectRatio(aspectRatio: l.width / l.height, child: DecoratedBox(
decoration: BoxDecoration(color: Colors.white, boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: .15), blurRadius: 8)]),
child: LayoutBuilder(builder: (_, box) => CustomPaint(painter: _Thumb(l, box.maxWidth / l.width))),
)));
},
),
),
),
ListTile(leading: Icon(widget.sample.icon, color: t.colorScheme.primary), title: Text(widget.sample.title, style: const TextStyle(fontWeight: FontWeight.w700)), subtitle: Text(widget.sample.subtitle, maxLines: 2)),
]),
),
);
}
}
class _Thumb extends CustomPainter {
_Thumb(this.l, this.scale);
final FlutterLayout l;
final double scale;
@override
void paint(Canvas canvas, Size size) => l.paintPage(canvas, 0, scale);
@override
bool shouldRepaint(_Thumb o) => o.l != l || o.scale != scale;
}
// ---- one report: view, data, template ----
class ReportPage extends StatefulWidget {
const ReportPage(this.sample, {super.key});
final Sample sample;
@override
State<ReportPage> createState() => _ReportPageState();
}
class _ReportPageState extends State<ReportPage> {
late Map<String, dynamic> data = widget.sample.data();
late final TextEditingController json = TextEditingController(text: const JsonEncoder.withIndent(' ').convert(data));
FlutterLayout? last;
bool busy = false;
String get fileName => '${widget.sample.title.toLowerCase().replaceAll(' ', '-')}.pdf';
Future<void> pdf({required bool share}) async {
setState(() => busy = true);
try {
final r = await renderer.render(await loadTemplate(widget.sample.asset), data: data);
if (share) {
await Printing.sharePdf(bytes: r.pdf, filename: fileName);
} else {
await Printing.layoutPdf(name: fileName, onLayout: (_) async => r.pdf);
}
if (mounted && r.hasWarnings) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(r.warnings.first)));
} finally {
if (mounted) setState(() => busy = false);
}
}
void apply(BuildContext context) {
try {
final d = (jsonDecode(json.text) as Map).cast<String, dynamic>();
setState(() => data = d);
DefaultTabController.of(context).animateTo(0);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Not valid JSON: $e')));
}
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return DefaultTabController(
length: 3,
child: Builder(builder: (context) => Scaffold(
appBar: AppBar(
title: Text(widget.sample.title),
actions: [
IconButton(tooltip: 'Print', onPressed: busy ? null : () => pdf(share: false), icon: const Icon(Icons.print_outlined)),
IconButton(tooltip: 'Share PDF', onPressed: busy ? null : () => pdf(share: true), icon: const Icon(Icons.ios_share)),
],
bottom: const TabBar(tabs: [Tab(icon: Icon(Icons.description_outlined), text: 'Report'), Tab(icon: Icon(Icons.data_object), text: 'Data'), Tab(icon: Icon(Icons.dashboard_customize_outlined), text: 'Template')]),
),
body: TabBarView(physics: const NeverScrollableScrollPhysics(), children: [
FutureBuilder(
future: loadTemplate(widget.sample.asset),
builder: (context, s) => !s.hasData ? const Center(child: CircularProgressIndicator()) : Column(children: [
if (last != null)
Container(
width: double.infinity,
color: last!.warnings.isEmpty ? cs.secondaryContainer : cs.errorContainer,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(last!.warnings.isEmpty ? '${last!.pages.length} page(s) · drawn by Flutter on this device' : '${last!.warnings.length} warning(s): ${last!.warnings.first}',
style: TextStyle(color: last!.warnings.isEmpty ? cs.onSecondaryContainer : cs.onErrorContainer)),
),
Expanded(child: FjReportView(report: s.data!, data: data, renderer: renderer, onLayout: (l) => WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) setState(() => last = l); }))),
]),
),
Padding(
padding: const EdgeInsets.all(16),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Text('This is the data the app passes to the report. Change it and render again.'),
const SizedBox(height: 12),
Expanded(child: TextField(controller: json, maxLines: null, expands: true, style: const TextStyle(fontFamily: 'monospace', fontSize: 13), decoration: const InputDecoration(border: OutlineInputBorder()))),
const SizedBox(height: 12),
FilledButton.icon(onPressed: () => apply(context), icon: const Icon(Icons.refresh), label: const Text('Render again')),
]),
),
FutureBuilder(
future: loadTemplate(widget.sample.asset),
builder: (context, s) {
if (!s.hasData) return const Center(child: CircularProgressIndicator());
final r = s.data!;
final (w, h) = r.page.dims;
return ListView(padding: const EdgeInsets.all(16), children: [
ListTile(leading: const Icon(Icons.description_outlined), title: Text(r.name), subtitle: Text('${widget.sample.asset} · ${r.page.size} ${w.round()} × ${h.round()} pt · ${r.page.locale}, ${r.page.currency}')),
const Divider(),
for (final b in r.bands) ListTile(dense: true, leading: const Icon(Icons.view_agenda_outlined), title: Text(b.kind), subtitle: Text('${b.els.length} items')),
const Divider(),
for (final d in r.datasets.entries) ListTile(dense: true, leading: Icon(d.value ? Icons.table_rows_outlined : Icons.data_object), title: Text(d.key), subtitle: Text(d.value ? 'list (table rows)' : 'single record')),
const SizedBox(height: 12),
const Card(child: Padding(padding: EdgeInsets.all(16), child: Text('Edit this template visually at fajfield.com/designer/report: open it, change anything, then Export → Template (.fjt). Replace the file in assets/ and the app prints the new layout.'))),
]);
},
),
]),
)),
);
}
}