10. Localization

Switching between Japanese and English with slang

Goals of this chapter

1

Translation files

ja / en JSON

2

Replace UI text

Reference it via context.t

3

Switch language

Applied instantly with a button

Preparation

flutter pub add 'slang:^4.0.0' 'slang_flutter:^4.0.0'
  • flutter_localizations was already added in Chapter 1

slang settings

Create slang.yaml in the project root.

slang.yaml
# Localization (slang) settings. Regenerate with `dart run slang` after changing translation files
base_locale: ja
fallback_strategy: base_locale
input_directory: lib/i18n
output_directory: lib/i18n
output_file_name: strings.g.dart
string_interpolation: braces
lazy: false
timestamp: false

Generate with dart run slang, not build_runner

slang can also generate via build_runner, but if the generated files are committed, build_runner fails right after cloning. Generating with the dedicated command avoids this problem.

Translation files

lib/i18n/ja.i18n.json

lib/i18n/ja.i18n.json
{
  "home": {
    "users": "ユーザー",
    "device": "デバイス",
    "language": "言語を切り替え"
  },
  "userList": {
    "title": "ユーザー一覧",
    "name": "名前",
    "add": "追加",
    "inputError": "名前を入力してください"
  },
  "userDetail": {
    "measure": "測定する",
    "history": "測定履歴",
    "noHistory": "まだ測定していません",
    "peakGyro": "最大角速度 {sensor1} / {sensor2} dps",
    "seconds": "{value}秒"
  },
  "measurement": {
    "title": "測定",
    "sensor": "センサ{no}  {value} dps",
    "elapsed": "{value} 秒",
    "start": "測定開始",
    "stopAndSave": "停止して保存",
    "personalBest": "自己ベスト更新!"
  },
  "device": {
    "title": "デバイス",
    "scan": "検索",
    "scanning": "検索中...",
    "fake": "偽物のセンサ(実機なし)",
    "saved": "保存されているデバイス",
    "connectFailed": "接続できませんでした",
    "reconnect": "再接続"
  },
  "connection": {
    "fake": "偽物",
    "connected": "接続済み",
    "battery": "電池 {value}%",
    "connecting": "接続中...",
    "disconnected": "未接続",
    "failed": "接続できません"
  }
}

lib/i18n/en.i18n.json

lib/i18n/en.i18n.json
{
  "home": {
    "users": "Users",
    "device": "Device",
    "language": "Switch language"
  },
  "userList": {
    "title": "Users",
    "name": "Name",
    "add": "Add",
    "inputError": "Please enter a name"
  },
  "userDetail": {
    "measure": "Measure",
    "history": "History",
    "noHistory": "No measurements yet",
    "peakGyro": "Peak angular velocity {sensor1} / {sensor2} dps",
    "seconds": "{value} s"
  },
  "measurement": {
    "title": "Measure",
    "sensor": "Sensor {no}  {value} dps",
    "elapsed": "{value} s",
    "start": "Start",
    "stopAndSave": "Stop and save",
    "personalBest": "New personal best!"
  },
  "device": {
    "title": "Device",
    "scan": "Scan",
    "scanning": "Scanning...",
    "fake": "Fake sensor (no hardware)",
    "saved": "Saved device",
    "connectFailed": "Could not connect",
    "reconnect": "Reconnect"
  },
  "connection": {
    "fake": "Fake",
    "connected": "Connected",
    "battery": "Battery {value}%",
    "connecting": "Connecting...",
    "disconnected": "Not connected",
    "failed": "Cannot connect"
  }
}

Generate the translation code

dart run slang   # creates lib/i18n/strings.g.dart, etc.
  • Run this command every time you change the translation files
  • The generated code follows the JSON hierarchy, as in context.t.home.users
  • Placeholders such as {value} are passed like context.t.userDetail.seconds(value: ...)

Wiring it into the app (main)

lib/main.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/app.dart';
import 'package:motion_app/i18n/strings.g.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/repository/settings/device_settings_repository.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized(); // Required when awaiting before runApp
  LocaleSettings.useDeviceLocaleSync(); // start in the device language
  // Load saved settings before startup → afterwards readable without await
  final prefs = await SharedPreferencesWithCache.create(
    cacheOptions: const SharedPreferencesWithCacheOptions(
      allowList: {DeviceSettingsRepository.deviceIdKey},
    ),
  );
  runApp(ProviderScope(
    overrides: [sharedPreferencesProvider.overrideWithValue(prefs)],
    child: TranslationProvider(child: const App()),
  ));
}
  • Use the device language at startup
  • Wrapping in TranslationProvider redraws screens that use context.t when the language changes

Wiring it into the app (MaterialApp)

lib/app.dart
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/router/router.dart';
import 'package:motion_app/i18n/strings.g.dart';

class App extends ConsumerWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Start connecting to the sensor right after launch (keeps the connection whichever screen is open)
    ref.listen(imuConnectionProvider, (_, _) {});
    return MaterialApp.router(
      title: 'Motion Note',
      theme: ThemeData(colorSchemeSeed: Colors.teal),
      routerConfig: ref.watch(routerProvider),
      locale: TranslationProvider.of(context).flutterLocale,
      supportedLocales: AppLocaleUtils.supportedLocales,
      localizationsDelegates: GlobalMaterialLocalizations.delegates,
    );
  }
}
  • Also match the language of Flutter’s built-in widgets (date pickers, etc.)

Replacing UI text

// Before
title: const Text('ユーザー'),
// After
title: Text(context.t.home.users),

// Interpolated values
Text(context.t.measurement.sensor(no: 1, value: state.gyro1.toStringAsFixed(0))),
  • Inside Widgets use context.t → redrawn automatically when the language changes
  • Remove const (the value is now determined at runtime)

Keep UI text out of the ViewModel

lib/ui/user_list/view_model/user_list_view_model.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/infrastructure/database/app_database.dart';
import 'package:motion_app/provider/providers.dart';

part 'user_list_view_model.g.dart';
part 'user_list_view_model.freezed.dart';

@freezed
abstract class UserListState with _$UserListState {
  const factory UserListState({
    @Default([]) List<User> users,
    @Default(true) bool isLoading,
    @Default(false) bool hasInputError, // the message is translated in the View
  }) = _UserListState;
}

@riverpod
class UserListViewModel extends _$UserListViewModel {
  @override
  UserListState build() {
    Future.microtask(load); // load when the screen is shown
    return const UserListState();
  }

  Future<void> load() async {
    final users = await ref.read(userRepositoryProvider).getAll();
    if (!ref.mounted) return; // do nothing if the screen was closed while waiting
    state = state.copyWith(users: users, isLoading: false);
  }

  // true if added
  Future<bool> addUser(String name) async {
    final trimmed = name.trim();
    if (trimmed.isEmpty) {
      state = state.copyWith(hasInputError: true);
      return false;
    }
    await ref.read(userRepositoryProvider).create(name: trimmed);
    if (!ref.mounted) return true;
    state = state.copyWith(hasInputError: false);
    await load();
    return true;
  }
}
  • The ViewModel holds only the fact of an error (errorMessage → hasInputError)
  • The View translates the message → it follows language switches

The list screen

lib/ui/user_list/view/user_list_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/router/router.dart';
import 'package:motion_app/ui/user_list/view_model/user_list_view_model.dart';
import 'package:motion_app/i18n/strings.g.dart';

class UserListPage extends HookConsumerWidget {
  const UserListPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(userListViewModelProvider);
    final notifier = ref.read(userListViewModelProvider.notifier);
    final nameController = useTextEditingController();

    return Scaffold(
      appBar: AppBar(title: Text(context.t.userList.title)),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: nameController,
                    decoration: InputDecoration(
                      labelText: context.t.userList.name,
                      errorText: state.hasInputError ? context.t.userList.inputError : null,
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                FilledButton(
                  onPressed: () async {
                    if (await notifier.addUser(nameController.text)) {
                      nameController.clear();
                    }
                  },
                  child: Text(context.t.userList.add),
                ),
              ],
            ),
          ),
          Expanded(
            child: state.isLoading
                ? const Center(child: CircularProgressIndicator())
                : ListView(
                    children: [
                      for (final user in state.users)
                        ListTile(
                          leading: const Icon(Icons.person),
                          title: Text(user.name),
                          onTap: () => context.push(Routes.userDetail(user.id)),
                        ),
                    ],
                  ),
          ),
        ],
      ),
    );
  }
}

The detail screen

lib/ui/user_detail/view/user_detail_page.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:motion_app/router/router.dart';
import 'package:motion_app/ui/user_detail/view_model/user_detail_view_model.dart';
import 'package:motion_app/i18n/strings.g.dart';

class UserDetailPage extends ConsumerWidget {
  const UserDetailPage({super.key, required this.userId});

  final String userId;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(userDetailViewModelProvider(userId));

    return Scaffold(
      appBar: AppBar(title: Text(state.user?.name ?? '')),
      floatingActionButton: FloatingActionButton.extended(
        icon: const Icon(Icons.sensors),
        label: Text(context.t.userDetail.measure),
        onPressed: () async {
          // The measurement screen returns true after saving, so reload the history
          final saved = await context.push<bool>(Routes.measurement(userId));
          if (saved == true) {
            ref.read(userDetailViewModelProvider(userId).notifier).load();
          }
        },
      ),
      body: state.isLoading
          ? const Center(child: CircularProgressIndicator())
          : ListView(
              padding: const EdgeInsets.all(16),
              children: [
                Text(context.t.userDetail.history),
                if (state.sessions.isEmpty) Text(context.t.userDetail.noHistory),
                for (final s in state.sessions)
                  ListTile(
                    leading: const Icon(Icons.timeline),
                    title: Text(context.t.userDetail.peakGyro(
                      sensor1: s.peakGyro1.toStringAsFixed(0),
                      sensor2: s.peakGyro2.toStringAsFixed(0),
                    )),
                    subtitle: Text(
                        '${DateFormat('yyyy/MM/dd HH:mm').format(s.recordedAt)}  '
                        '${context.t.userDetail.seconds(value: s.durationSec.toStringAsFixed(1))}'),
                  ),
              ],
            ),
    );
  }
}

The measurement screen

lib/ui/measurement/view/measurement_page.dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/ui/common/connection_status_chip.dart';
import 'package:motion_app/ui/measurement/view_model/measurement_view_model.dart';
import 'package:motion_app/i18n/strings.g.dart';

class MeasurementPage extends ConsumerWidget {
  const MeasurementPage({super.key, required this.userId});

  final String userId;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(measurementViewModelProvider(userId));
    final notifier = ref.read(measurementViewModelProvider(userId).notifier);
    // Pick only the needed value with select → no redraw when the battery level changes
    final isConnected = ref.watch(imuConnectionProvider
        .select((s) => s.status == ImuConnectionStatus.connected));
    final big = Theme.of(context).textTheme.displaySmall;

    return Scaffold(
      appBar: AppBar(
        title: Text(context.t.measurement.title),
        actions: const [ConnectionStatusChip()],
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(context.t.measurement.sensor(no: 1, value: state.gyro1.toStringAsFixed(0)), style: big),
            Text(context.t.measurement.sensor(no: 2, value: state.gyro2.toStringAsFixed(0)), style: big),
            const SizedBox(height: 8),
            Text(context.t.measurement.elapsed(value: (state.sampleCount / 100).toStringAsFixed(1))),
            const SizedBox(height: 32),
            state.isMeasuring
                ? FilledButton.icon(
                    icon: const Icon(Icons.stop),
                    label: Text(context.t.measurement.stopAndSave),
                    onPressed: () async {
                      final result = await notifier.stopAndSave();
                      if (result == null || !context.mounted) return;
                      if (result.isPersonalBest) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text(context.t.measurement.personalBest)),
                        );
                      }
                      context.pop(true);
                    },
                  )
                : FilledButton.icon(
                    icon: const Icon(Icons.play_arrow),
                    label: Text(context.t.measurement.start),
                    onPressed: isConnected ? notifier.start : null, // disabled until connected
                  ),
          ],
        ),
      ),
    );
  }
}

The device screen

lib/ui/device/view/device_page.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/ui/common/connection_status_chip.dart';
import 'package:motion_app/ui/device/view_model/device_view_model.dart';
import 'package:motion_app/i18n/strings.g.dart';

class DevicePage extends ConsumerWidget {
  const DevicePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(deviceViewModelProvider);
    final notifier = ref.read(deviceViewModelProvider.notifier);
    final selectedId = ref.watch(selectedBleDeviceProvider);
    final connection = ref.watch(imuConnectionProvider);
    // A device that is saved but not in this scan's results
    final isSavedOnly = selectedId != null &&
        state.devices.every((d) => d.deviceId != selectedId);

    return Scaffold(
      appBar: AppBar(
        title: Text(context.t.device.title),
        actions: const [ConnectionStatusChip()],
      ),
      floatingActionButton: FloatingActionButton.extended(
        icon: const Icon(Icons.bluetooth_searching),
        label: Text(state.isScanning ? context.t.device.scanning : context.t.device.scan),
        onPressed: state.isScanning ? null : notifier.scan,
      ),
      body: RadioGroup<String?>(
        groupValue: selectedId,
        onChanged: notifier.select,
        child: ListView(
          children: [
            RadioListTile<String?>(
              value: null,
              title: Text(context.t.device.fake),
            ),
            if (isSavedOnly)
              RadioListTile<String?>(
                value: selectedId,
                title: Text(context.t.device.saved),
                subtitle: Text(selectedId),
              ),
            if (connection.hasError)
              ListTile(
                leading: const Icon(Icons.error_outline),
                title: Text(context.t.device.connectFailed),
                trailing: TextButton(
                  onPressed: notifier.reconnect,
                  child: Text(context.t.device.reconnect),
                ),
              ),
            if (state.errorMessage != null)
              ListTile(title: Text(state.errorMessage!)),
            for (final device in state.devices)
              RadioListTile<String?>(
                value: device.deviceId,
                title: Text(device.name ?? ''),
                subtitle: Text('${device.deviceId}  RSSI ${device.rssi ?? '-'}'),
              ),
          ],
        ),
      ),
    );
  }
}

Connection-state display

lib/ui/common/connection_status_chip.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/i18n/strings.g.dart';

// Sensor connection state and battery level. Can be placed in any screen's AppBar
class ConnectionStatusChip extends ConsumerWidget {
  const ConnectionStatusChip({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final connection = ref.watch(imuConnectionProvider);
    final isFake = ref.watch(selectedBleDeviceProvider) == null;
    final battery = connection.batteryLevel;
    final t = context.t.connection;

    final (icon, label) = switch (connection.status) {
      ImuConnectionStatus.connected => (
          Icons.bluetooth_connected,
          '${isFake ? t.fake : t.connected}${battery == null ? '' : '  ${t.battery(value: battery)}'}',
        ),
      ImuConnectionStatus.connecting => (Icons.bluetooth_searching, t.connecting),
      ImuConnectionStatus.disconnected => (
          Icons.bluetooth_disabled,
          connection.hasError ? t.failed : t.disconnected,
        ),
    };
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      child: Chip(avatar: Icon(icon, size: 18), label: Text(label)),
    );
  }
}
  • Putting an intermediate level in a variable, like context.t.connection, keeps the code short

Home and the language toggle button

lib/ui/home/view/home_page.dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:motion_app/router/router.dart';
import 'package:motion_app/ui/common/connection_status_chip.dart';
import 'package:motion_app/i18n/strings.g.dart';

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Motion Note'),
        actions: [
          const ConnectionStatusChip(),
          IconButton(
            icon: const Icon(Icons.translate),
            tooltip: context.t.home.language,
            // Toggle Japanese ⇔ English. Screens using context.t are redrawn automatically
            onPressed: () => LocaleSettings.setLocaleSync(
              LocaleSettings.currentLocale == AppLocale.ja ? AppLocale.en : AppLocale.ja,
            ),
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          Card(
            child: ListTile(
              leading: const Icon(Icons.people),
              title: Text(context.t.home.users),
              trailing: const Icon(Icons.chevron_right),
              onTap: () => context.push(Routes.users),
            ),
          ),
          Card(
            child: ListTile(
              leading: const Icon(Icons.bluetooth),
              title: Text(context.t.home.device),
              trailing: const Icon(Icons.chevron_right),
              onTap: () => context.push(Routes.device),
            ),
          ),
        ],
      ),
    );
  }
}
dart run slang analyze   # check for missing translations

Checkpoint

CHECK 0 / 5