Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting BuildContext in Flutter for localization

Tags:

flutter

dart

I try to localize a String in Flutter with the localization package. The problem is the location where my translation is needed. It is not related to the UI, rather it is somewhere deep in my model, where I don't have access to a BuildContext. Is there any other possibility to still make use of the translation function?

// I don't have a context variable here
MyLocalizations.of(context).trans("foo")
like image 614
Daniel Stephens Avatar asked Aug 11 '18 21:08

Daniel Stephens


People also ask

What does BuildContext do in Flutter?

BuildContext is a locator that is used to track each widget in a tree and locate them and their position in the tree. The BuildContext of each widget is passed to their build method. Remember that the build method returns the widget tree a widget renders. Each BuildContext is unique to a widget.

How do you add multi language support to your Flutter app via dynamic localization?

Just click on Tools > Flutter Intl > Add Locale. This will open a popup where you can write the name of the . arb file for the particular language. Let's add support for the Hindi language, so enter.

How do you get the Flutter app multi language?

By default, Flutter only provides US English localizations. To add support for other languages, an application must specify additional MaterialApp (or CupertinoApp ) properties, and include a package called flutter_localizations . As of November 2020, this package supports 78 languages.


1 Answers

Yes there is. You don't need BuildContext to access strings. Here is my solution:

class Strings {
  Strings._(Locale locale) : _localeName = locale.toString() {
    current = this;
  }

  final String _localeName;

  static Strings current;

  static Future<Strings> load(Locale locale) async {
    await initializeMessages(locale.toString());
    final result = Strings._(locale);
    return result;
  }

  static Strings of(BuildContext context) {
    return Localizations.of<Strings>(context, Strings);
  }

  String get title {
    return Intl.message(
      'Hello World',
      name: 'title',
      desc: 'Title for the Demo application',
    );
  }
}

Future<Null> main() async {
  final Locale myLocale = Locale(window.locale);
  await Strings.load(myLocale);
  runApp(MyApplication());
}

Now you can reference a string as follows:

final title = Strings.current.title;
like image 124
kine Avatar answered Oct 01 '22 01:10

kine