ThorMJ
ThorMJ

Reputation: 89

How to you change the locale of a flutter app while running?

I'm using

import 'package:flutter_localizations/flutter_localizations.dart'; //For Cupertino stuff
import 'package:localization/localization.dart'; //For actual translations
import 'package:intl/intl.dart'; //For locales

to localize my flutter app. It comes up in the language the phone is set to, but I'd like to add a way to change the language within th e app...I tried using LocalJsonLocalization.delegate.load(locale(lang)) from a button (for now; I'd like to use a dropdown list box but that doesn't seem to be null safe yet), but that didn't actually make the change (I saw the debug log and it said it couldn't load the json language file)...

Upvotes: 0

Views: 2181

Answers (1)

luisv
luisv

Reputation: 156

Try wrapping your MaterialApp in a BlocBuilder.

return BlocBuilder<MainBloc, MainState>(
  builder: (context, mainState) {
    return MaterialApp(
      title: 'MyApp',
      locale: mainState.locale,
      supportedLocales: L10n.all,
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
    );

Then from your button just call the Bloc Event that will change the state of the locale.

Do not forget to add:

WidgetsFlutterBinding.ensureInitialized();

at the beginning of main() function

It should also work fine using Provider.

Upvotes: 1

Related Questions