Skip to main content

siyak_flutter 0.1.0 copy "siyak_flutter: ^0.1.0" to clipboard
siyak_flutter: ^0.1.0 copied to clipboard

Context-aware translation for Flutter: a cache-first t() that never blocks, with background batching and a persistent LRU cache.

example/lib/main.dart

// A minimal, right-to-left-aware Siyak demo.
//
// Run it with a test key:
//   flutter run --dart-define=SIYAK_API_KEY=sk_test_… --dart-define=SIYAK_TARGET=ar-EG
// Against a local Worker, pass --dart-define=SIYAK_ENDPOINT=http://localhost:8787
// (and allowInsecureEndpoint: true below).
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:siyak_flutter/siyak_flutter.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  final siyak = Siyak.init(
    apiKey: const String.fromEnvironment('SIYAK_API_KEY', defaultValue: 'sk_test_replace_me'),
    target: const String.fromEnvironment('SIYAK_TARGET', defaultValue: 'ar-EG'),
    // No compiled-in host: run with
    //   flutter run --dart-define=SIYAK_ENDPOINT=https://your-dashboard-host
    // — the exact URL is on the dashboard's API-key screen. Omitting it makes
    // Siyak.init throw at startup instead of talking to a guessed domain.
    endpoint: const String.fromEnvironment('SIYAK_ENDPOINT'),
    source: 'en',
    // One context for the whole demo: "account" on a billing screen and on a
    // profile screen are different strings, and the server treats them so.
    context: 'demo home screen',
    onLog: (message) => debugPrint('[siyak] $message'),
  );

  // One request that fills the cache with every approved string the project
  // has. Unawaited: the first frame must not wait on the network.
  unawaited(siyak.preload());

  runApp(SiyakDemoApp(siyak: siyak));
}

/// Strings this screen shows, in the source language.
const List<String> demoLabels = <String>[
  'Settings',
  'My account',
  'Notifications',
  'Payment method',
  'Sign out',
  'Save changes',
];

class SiyakDemoApp extends StatelessWidget {
  const SiyakDemoApp({required this.siyak, super.key});

  final Siyak siyak;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Siyak demo',
      theme: ThemeData(useMaterial3: true, colorSchemeSeed: const Color(0xFF0F766E)),
      home: SiyakHomePage(siyak: siyak),
    );
  }
}

class SiyakHomePage extends StatefulWidget {
  const SiyakHomePage({required this.siyak, super.key});

  final Siyak siyak;

  @override
  State<SiyakHomePage> createState() => _SiyakHomePageState();
}

class _SiyakHomePageState extends State<SiyakHomePage> {
  late final Siyak _siyak = widget.siyak;

  /// Lets the operator pin the layout direction, to see the RTL bug and its fix.
  bool _followLanguageDirection = true;

  @override
  void initState() {
    super.initState();
    // THE rebuild pattern for a synchronous t(): the first frame paints the
    // source text, the batch lands ~200ms later, and this listener repaints.
    _siyak.translationRevision.addListener(_onTranslationsChanged);
  }

  void _onTranslationsChanged() {
    if (mounted) setState(() {});
  }

  @override
  void dispose() {
    _siyak.translationRevision.removeListener(_onTranslationsChanged);
    super.dispose();
  }

  /// Direction for the whole subtree. A translated Arabic string is RTL even
  /// though the app's own layout, and the source text, were LTR.
  TextDirection get _direction {
    if (!_followLanguageDirection) return TextDirection.ltr;
    return _siyak.isRightToLeft ? TextDirection.rtl : TextDirection.ltr;
  }

  Future<void> _warmUpAndRefresh() async {
    // Fills the cache for these strings in one batched call, so the next frame
    // is already translated instead of animating into place.
    await _siyak.warmUp(demoLabels);
  }

  Future<void> _translateOnDemand() async {
    // A string being produced right now, not one being laid out: await it.
    final shared = await _siyak.translate('Your order is ready, thank you!', context: 'push notification');
    if (!mounted) return;
    // SnackBar takes its direction from the enclosing Directionality, so wrap it
    // rather than hunt for a per-widget override.
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Directionality(textDirection: _direction, child: Text(shared)),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_siyak.t('Settings')),
        // The title string can flip direction while the bar itself does not.
        titleTextStyle: Theme.of(context).textTheme.titleLarge?.copyWith(color: Colors.white),
      ),
      body: Column(
        children: <Widget>[
          _ErrorBanner(siyak: _siyak),
          SwitchListTile(
            title: Text(_siyak.t('Notifications')),
            secondary: const Icon(Icons.translate_rounded),
            value: _followLanguageDirection,
            onChanged: (value) => setState(() => _followLanguageDirection = value),
          ),
          Expanded(
            child: Directionality(
              // Everything inside inherits this. Toggle the switch above with a
              // Arabic target and watch 'Sign out' move from the left edge to
              // the right one — the same string, the correct side.
              textDirection: _direction,
              child: ListView(
                children: <Widget>[
                  for (final label in demoLabels)
                    ListTile(
                      leading: const Icon(Icons.label_outline_rounded),
                      title: Text(_siyak.t(label)),
                      subtitle: Text(
                        // Mixed content: an LTR brand name inside an RTL line.
                        // textDirection alone is not enough — let the paragraph
                        // algorithm resolve it from the strongest run.
                        '${_siyak.t('Payment method')}: Visa •••• 4242',
                        textDirection: _direction,
                      ),
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          children: <Widget>[
            TextButton.icon(
              onPressed: _warmUpAndRefresh,
              icon: const Icon(Icons.bolt_rounded),
              label: Text(_siyak.t('Translate the list now')),
            ),
            const Spacer(),
            TextButton.icon(
              onPressed: _translateOnDemand,
              icon: const Icon(Icons.share_rounded),
              label: Text(_siyak.t('Share the order status')),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => debugPrint('${_siyak.cachedStringCount} cached strings'),
        child: const Icon(Icons.language_rounded),
      ),
    );
  }
}

/// Surfaces `lastError` without ever blocking a translation.
class _ErrorBanner extends StatelessWidget {
  const _ErrorBanner({required this.siyak});

  final Siyak siyak;

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<String?>(
      valueListenable: siyak.lastError,
      builder: (context, code, child) {
        if (code == null) return const SizedBox.shrink();
        final parked = siyak.isParked;
        return Material(
          color: code == 'quota_exceeded' || code == 'rate_limited' ? const Color(0xFFFFF1B2) : const Color(0xFFFDECEC),
          child: ListTile(
            leading: const Icon(Icons.error_outline_rounded),
            title: Text('Siyak: $code${parked ? ' — cached strings still work' : ''}'),
            trailing: parked
                ? TextButton(
                    onPressed: () => siyak.resume(),
                    child: const Text('Retry'),
                  )
                : null,
          ),
        );
      },
    );
  }
}
0
likes
160
points
19
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Context-aware translation for Flutter: a cache-first t() that never blocks, with background batching and a persistent LRU cache.

Homepage

Topics

#i18n #localization #translation #arabic

License

MIT (license)

Dependencies

flutter, http, shared_preferences

More

Packages that depend on siyak_flutter