flutter_localisation 2.0.0

SDKflutter
Platformandroidioswindowslinuxmacosweb

A command-line tool for generating localization files for different flavors.

SaaS Translations 🚀

A Flutter package that adds SaaS-based dynamic translation overrides to your existing Flutter localization setup. Get translations from your API and override them at runtime without app updates!

✨ Features

  • Zero Configuration: Auto-detects your generated localizations
  • Dynamic Overrides: Fetch translations from your API at runtime
  • Type Safe: Auto-generates methods for all your translations
  • Fallback Support: Uses generated localizations when no override exists
  • Hot Reload Friendly: Updates UI immediately when translations change
  • Production Ready: Configurable timeouts, error handling, caching

🚀 Quick Start

1. Add to pubspec.yaml

dependencies:
  saas_translations: ^1.0.0

  # Your existing localization setup
  flutter_localizations:
    sdk: flutter
  intl: any

2. Generate your methods

# Generate standard Flutter localizations first
flutter gen-l10n

# Generate SaaS translation methods
dart pub run saas_translations:generate

3. Wrap your app

import 'package:saas_translations/saas_translations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _saasService = SaaSTranslationService();
  Key _appKey = UniqueKey();

  @override
  void initState() {
    super.initState();
    _saasService.addListener(_onTranslationsUpdated);

    // Fetch translations after first frame
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _saasService.fetchUpdates('en');
    });
  }

  void _onTranslationsUpdated() {
    if (mounted) {
      setState(() => _appKey = UniqueKey());
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      key: _appKey,

      // Your existing localization setup
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,

      // Add SaaS provider
      builder: (context, child) {
        final localizations = AppLocalizations.of(context)!;

        return SaaSTranslationProvider(
          service: _saasService,
          generatedLocalizations: localizations,
          child: child!,
        );
      },

      home: HomePage(),
    );
  }
}

4. Use translations

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.tr.appTitle), // 🎯 Simple usage!
      ),
      body: Column(
        children: [
          Text(context.tr.hello("World")),           // ✨ Type safe
          Text(context.tr.welcomeMessage("User")),   // ✨ Auto-complete
          Text(context.tr.itemsInCart(5)),          // ✨ Plurals work

          ElevatedButton(
            onPressed: () => context.tr.refresh(),   // 🔄 Manual refresh
            child: Text('Refresh Translations'),
          ),
        ],
      ),
    );
  }
}

🔧 Custom API Integration

Override the fetchUpdates method to integrate with your API:

class MyTranslationService extends SaaSTranslationService {
  @override
  Future<Map<String, String>> _fetchFromAPI(String locale) async {
    final response = await http.get(
      Uri.parse('https://your-api.com/translations/$locale'),
    );

    if (response.statusCode == 200) {
      final data = json.decode(response.body) as Map<String, dynamic>;
      return data.cast<String, String>();
    }

    return {};
  }
}

⚙️ Configuration

final service = SaaSTranslationService(
  config: SaaSTranslationConfig(
    apiTimeout: Duration(seconds: 10),     // API timeout
    enableLogging: true,                   // Debug logging
    throwOnError: false,                   // Silent fail vs throw
  ),
);

// Or use presets
SaaSTranslationConfig.development()  // Fast, verbose logging
SaaSTranslationConfig.production()   // Secure, error throwing

📁 Project Structure

The package automatically detects your project structure:

your_app/
├── lib/
│   ├── l10n/                          # Your ARB files
│   │   ├── app_en.arb
│   │   └── app_es.arb
│   ├── generated/                     # Flutter gen-l10n output
│   │   └── app_localizations.dart
│   └── generated_saas_methods.dart    # Auto-generated by our package
├── l10n.yaml                          # Flutter l10n config
└── pubspec.yaml

🔄 Workflow

  1. Create/update ARB files → lib/l10n/app_en.arb
  2. Generate Flutter localizations → flutter gen-l10n
  3. Generate SaaS methods → dart pub run saas_translations:generate
  4. Use in your app → context.tr.yourMethod()

🚦 How It Works

  1. First Check: SaaS override from your API
  2. Fallback: Generated Flutter localizations
  3. Auto-Rebuild: UI updates when translations change
  4. Type Safety: All methods auto-generated with correct signatures

💡 Pro Tips

  • Hot Reload Friendly: Changes apply immediately during development
  • Offline Support: Falls back to bundled translations when API fails
  • Plurals & ICU: Full support for complex localization features
  • Caching: Translations are cached until next app restart
  • Debug Mode: Enable logging to see what's happening

📱 Example App

Check out the example app for a complete working implementation!

🤝 Contributing

We welcome contributions! Please see our Contributing Guide.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.