Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localization in Flutter MaterialApp Widget parameters

Following the tutorials at 1 and 2 I am trying to set up localization for my flutter app. That works fine and I can use I18n.of(context).trans(<key>) to access translated strings in my widgets.

However I don't know how to access the translations in the MaterialApp top widget:

import 'package:flutter/material.dart';
import 'package:flutter_app/i18n/i18n.dart';
import 'package:flutter_app/views/menu.dart';
import 'package:flutter\_localizations/flutter\_localizations.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      supportedLocales: [
        const Locale('en', 'US'),
        const Locale('de', 'DE'),
      ],
      localizationsDelegates: [
        const I18nDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],

      title: I18n.of(context).trans('title'), //FIXME doesn't work
      home: new Menu(),

    );
  }
}

For above code I get an exception because I18n.of(context) returns null. What am I missing?

like image 916
Andreas Gohr Avatar asked Jun 20 '18 23:06

Andreas Gohr


1 Answers

You should use onGenerateTitle instead of title field :

MaterialApp(
   ...
   onGenerateTitle: (context) => I18n.of(context).trans('title'),
)
like image 89
Rémi Rousselet Avatar answered Oct 24 '22 20:10

Rémi Rousselet