localization_by_muz 1.0.3 copy "localization_by_muz: ^1.0.3" to clipboard
localization_by_muz: ^1.0.3 copied to clipboard

A simple Flutter package for easy localization with inline text support and JSON-based translations

[Localization by Muz banner]

Localization by Muz #

A simple Flutter package for easy localization with inline text support and JSON-based translations. No extra commands, no code generation - just add the package and start localizing!

Features #

  • Inline Localization: Use .localize() method directly on strings with inline translations
  • JSON-based Localization: Use a simple JSON file for organized translations
  • Parameter Interpolation: Support for dynamic text with placeholders like {name} via args map
  • Custom Asset Loading: Pluggable asset loaders including per-locale files and composite strategies
  • Instant Language Switching: Change languages instantly without app restart
  • No Code Generation: No need for build runner or code generation commands
  • Simple Setup: Just add the package and start using

Getting Started #

Add the package to your pubspec.yaml:

dependencies:
  localization_by_muz: ^1.0.3

Usage #

Method 1: Inline Localization #

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LocalizationProvider(
      defaultLocale: 'en',
      child: MaterialApp(
        home: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Hello World!".localize({
          "en": "Hello World!",
          "fr": "Bonjour le monde!",
          "es": "¡Hola Mundo!"
        })),
      ),
      body: Column(
        children: [
          Text("Welcome".localize({
            "en": "Welcome",
            "fr": "Bienvenue",
            "es": "Bienvenido"
          })),
          ElevatedButton(
            onPressed: () => LocalizationProvider.setLocale(context, 'fr'),
            child: Text("Switch to French"),
          ),
          ElevatedButton(
            onPressed: () => LocalizationProvider.setLocale(context, 'en'),
            child: Text("Switch to English"),
          ),
        ],
      ),
    );
  }
}

Method 2: JSON-based Localization #

  1. Create a localization.json file in your lib/ directory (required path for this package):
{
  "helloWorld": {
    "en": "Hello World",
    "fr": "Bonjour Le Monde",
    "es": "Hola Mundo"
  },
  "welcome": {
    "en": "Welcome", 
    "fr": "Bienvenue",
    "es": "Bienvenido"
  },
  "goodbye": {
    "en": "Goodbye",
    "fr": "Au revoir", 
    "es": "Adiós"
  }
}
  1. Add it to your app's pubspec.yaml assets so Flutter bundles it:
flutter:
  assets:
    - lib/localization.json

Note: The package reads from lib/localization.json via rootBundle. Keep this exact path and add it to assets as shown above.

  1. Use in your Flutter app:
import 'package:flutter/material.dart';
import 'package:localization_by_muz/localization_by_muz.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LocalizationProvider(
      defaultLocale: 'en',
      child: MaterialApp(
        home: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("helloWorld".localize()),
      ),
      body: Column(
        children: [
          Text("welcome".localize()),
          Text("goodbye".localize()),
          ElevatedButton(
            onPressed: () => LocalizationProvider.setLocale(context, 'fr'),
            child: Text("Switch to French"),
          ),
          ElevatedButton(
            onPressed: () => LocalizationProvider.setLocale(context, 'es'),
            child: Text("Switch to Spanish"),
          ),
        ],
      ),
    );
  }
}

Language Switching #

To change the language instantly:

LocalizationProvider.setLocale(context, 'fr'); // Switch to French
LocalizationProvider.setLocale(context, 'en'); // Switch to English
LocalizationProvider.setLocale(context, 'es'); // Switch to Spanish

The UI will update instantly without requiring app restart or refresh!

Parameter Interpolation #

Support for dynamic text with placeholders:

// Inline translations with parameters
Text("greeting".localizeArgs(
  translations: {
    "en": "Hello {name}, welcome to {app}!",
    "fr": "Bonjour {name}, bienvenue dans {app}!",
    "es": "¡Hola {name}, bienvenido a {app}!"
  },
  args: {
    "name": "John",
    "app": "My App"
  }
))

// JSON-based translations with parameters
// In localization.json:
// {
//   "userWelcome": {
//     "en": "Welcome back, {username}!",
//     "fr": "Bon retour, {username}!"
//   }
// }

Text("userWelcome".localizeArgs(
  args: {"username": "Alice"}
))

Custom Asset Loading #

Use different asset loading strategies:

// Per-locale files (assets/i18n/en.json, fr.json, etc.)
LocalizationProvider(
  defaultLocale: 'en',
  assetLoader: PerLocaleAssetLoader(basePath: 'assets/i18n'),
  child: MyApp(),
)

// Composite loading (combine multiple loaders)
LocalizationProvider(
  defaultLocale: 'en',
  assetLoader: CompositeAssetLoader([
    DefaultAssetLoader(),
    PerLocaleAssetLoader(basePath: 'assets/i18n'),
  ]),
  child: MyApp(),
)

Missing Key Diagnostics #

Track and debug missing translation keys:

// Enable logging and debug overlay
LocalizationProvider(
  defaultLocale: 'en',
  enableMissingKeyLogging: true,
  showDebugOverlay: true, // Only works in debug mode
  onMissingKey: (key, locale) {
    print('Missing key: $key for locale: $locale');
    // Send to analytics, log to file, etc.
  },
  child: MyApp(),
)

// Configure at runtime
LocalizationManager.instance.configureMissingKeyDiagnostics(
  enableLogging: true,
  onMissingKey: (key, locale) {
    // Handle missing keys
  },
);

// Access missing keys
Set<String> missingKeys = LocalizationManager.instance.missingKeys;

// Clear tracked missing keys
LocalizationManager.instance.clearMissingKeys();

Hot-reload Translations (Debug Mode) #

Enable automatic reloading of translations during development for faster iteration:

LocalizationProvider(
  defaultLocale: 'en',
  enableHotReload: true, // Enable hot-reload in debug mode
  child: MyApp(),
)

Features:

  • Debug-only: Hot-reload only works in debug mode for performance
  • Automatic detection: Checks for translation changes every 2 seconds
  • Live updates: UI updates automatically when translations change
  • Error handling: Gracefully handles asset loading failures
  • Performance optimized: Only reloads when actual changes are detected

How it works:

// Hot-reload is automatically enabled when:
// 1. enableHotReload: true is set
// 2. App is running in debug mode
// 3. Asset loader is available

// Console output when hot-reload is active:
// 🔥 Hot-reload enabled for translations (checking every 2 seconds)
// 🔄 Translation changes detected, reloading...
// ✅ Translations reloaded successfully

Note: Hot-reload requires your translations to be loaded from assets. It works with all asset loaders including DefaultAssetLoader, PerLocaleAssetLoader, and custom implementations.

Features Breakdown #

  • Two localization methods: Choose between inline translations or JSON file approach
  • Parameter interpolation: Dynamic text with {placeholder} support via .localizeArgs(args: {...})
  • Custom asset loading: Pluggable loaders (DefaultAssetLoader, PerLocaleAssetLoader, CompositeAssetLoader, MemoryAssetLoader)
  • Missing key diagnostics: Toggleable logs, onMissingKey callback, optional debug overlay
  • Hot-reload translations: Automatic translation reloading in debug mode for faster development
  • Instant updates: Language changes reflect immediately in the UI
  • Zero configuration: No build runner or code generation required
  • Simple API: Just use .localize() on any string
  • Fallback support: If translation not found, returns original text
  • Provider pattern: Efficient state management using Flutter's provider pattern

Additional Information #

This package is designed to make Flutter localization as simple as possible. Whether you prefer inline translations for small projects or JSON files for larger applications, this package has you covered.

For issues and feature requests, please visit our GitHub repository.

Author #

Muzamil Ghafoor


Made By Muzamil Ghafoor With ❤️ For The Flutter Developers To Make Localization Easy

1
likes
0
points
9
downloads

Publisher

verified publishermuz.satech.dev

Weekly Downloads

A simple Flutter package for easy localization with inline text support and JSON-based translations

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

flutter

More

Packages that depend on localization_by_muz