localizely / flutter-intl-intellij

This Android Studio & IntelliJ plugin generates boilerplate code for localization of Flutter apps with official Dart Intl library
MIT License
129 stars 4 forks source link

S.load doesn't work when called from the `main` function #100

Closed iLoveDocs closed 1 year ago

iLoveDocs commented 1 year ago

Issue:

When attempting to change the locale using S.load(...) from the main function, the S.current reference still points to the old locale.

Minimal reproducible code:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await S.load(Locale('de')); // Doesn't work!
  runApp(
    MaterialApp(
      localizationsDelegates: [S.delegate],
      supportedLocales: S.delegate.supportedLocales,
      home: FooPage(),
    ),
  );
}

class FooPage extends StatefulWidget {
  @override
  State<FooPage> createState() => _FooPageState();
}

class _FooPageState extends State<FooPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => S.load(Locale('de')).then((_) => setState(() {})), // Works
        label: Text(S.current.hello),
      ),
    );
  }
}

When running the app, the button displays "Hello". Even if a hot reload is performed, it continues to display "Hello". However, pressing the FloatingActionButton (FAB) displays "Hallo".

Putting S.load(...) in the _FooPageState.initState callback results in the expected behavior.

lzoran commented 1 year ago

Thanks for pointing that out. Indeed, setting the locale before localizationsDelegates will not yield the desired result.

To start your app with a specific locale, you might find the following snippet helpful:

void main() async {
  runApp(
    MaterialApp(
      localizationsDelegates: const [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: S.delegate.supportedLocales,
      locale: const Locale('de'), // Explicit setting of the locale
      home: FooPage(),
    ),
  );
}

For implementing a language switcher in Flutter app, maybe this approach might be of help.