DEV Community

Mostafa Ead
Mostafa Ead

Posted on

Auto-Generate Flutter Translations

Stop forgetting to regenerate your Flutter translations! πŸš€

I got tired of manually running dart run intl_utils:generate every time I edited my .arb translation files. So I automated it with a simple file watcher script.

How to use it:
Just run this command in your terminal:

dart run scripts/watch_translations.dart
Enter fullscreen mode Exit fullscreen mode

The script will watch your lib/l10n directory and automatically regenerate translations whenever you modify any .arb file.

Here's the implementation:

import 'dart:io';

void main() async {
  final l10nDir = Directory('lib/l10n');

  if (!l10nDir.existsSync()) {
    print('Error: lib/l10n directory does not exist');
    exit(1);
  }

  print('Watching for changes in lib/l10n/*.arb files...');
  print('Press Ctrl+C to stop\n');

  // Watch the directory
  await for (final event in l10nDir.watch()) {
    if (event.path.endsWith('.arb') && event.type == FileSystemEvent.modify) {
      print('Detected change in: ${event.path}');
      print('Generating translations...');

      final result = await Process.run(
        'dart',
        ['run', 'intl_utils:generate'],
        runInShell: true,
      );

      if (result.exitCode == 0) {
        print('βœ“ Translations generated successfully\n');
      } else {
        print('βœ— Error generating translations:');
        print(result.stderr);
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

What it does:
βœ… Monitors the lib/l10n directory for changes to .arb files
βœ… Detects when translation files are modified
βœ… Automatically runs the translation generation command
βœ… Provides clear feedback on success or failure

Now I can edit translation files and the generated code updates automatically. No more manual steps or missed regenerations.

The script uses Dart's built-in Directory.watch() API to monitor file system events. It's lightweight, runs in the background, and has been a huge time-saver.

Sometimes the best solutions are the simplest ones that remove friction from your workflow.

Flutter #Dart #MobileDevelopment #DeveloperProductivity #Automation #FlutterDev #Coding #SoftwareDevelopment

Top comments (0)