Search code examples
flutterlocalizationinitialization

use of device language setting for flutter internationalization as default


sorry I still struggle with the setting of the locale provider for the internationalization of my app. I want to program my app, that the default language is selected via the language setting of the device. If the user wants to have a different language he or she should be able to pick one via dropdown menu in the app bar as well. the code works fine for either solution, but I wasn't able to combine the two tasks. Is there a possibility to Initialize the _locale to the device settings? I tried to implement the

Locale myLocale = Localizations.localeOf(context);

but this didnt work . Next I tried to import 'package:devicelocale/devicelocale.dart'; but unfortunately this didnt work as well

here's my code:

import 'package:flutter/material.dart';

import 'package:esosba_app/l10n/l10n.dart';


class LocaleProvider extends ChangeNotifier {
  Locale _locale;

  LocaleProvider()
      : _locale = const Locale('en'); // Initialize _locale to English. Is a device setting language possible?

  Locale get locale => _locale;

  void setLocale(Locale locale) {
    if (!L10n.all.contains(locale)) return;

    _locale = locale;
    notifyListeners();
  }

  void clearLocale() {
    _locale = const Locale('en'); // Reset _locale to English
    notifyListeners();
  }
}

I m looking forward to your answers Kind regards


Solution

  • I was able to manage it by using the dart ui first import import 'dart:ui'as ui; final locale = provider.locale ?? Locale(ui.window.locale.languageCode); and now it works