【问题标题】:Localization in Flutter MaterialApp Widget parametersFlutter MaterialApp Widget 参数中的本地化
【发布时间】:2018-06-20 23:56:12
【问题描述】:

按照12 的教程,我正在尝试为我的颤振应用程序设置本地化。这很好用,我可以使用 I18n.of(context).trans(<key>) 在我的小部件中访问翻译后的字符串。

但我不知道如何访问 MaterialApp 顶部小部件中的翻译:

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(),

    );
  }
}

对于上面的代码,我得到一个异常,因为I18n.of(context) 返回null。我错过了什么?

【问题讨论】:

    标签: localization flutter


    【解决方案1】:

    您应该使用onGenerateTitle 而不是title 字段:

    MaterialApp(
       ...
       onGenerateTitle: (context) => I18n.of(context).trans('title'),
    )
    

    【讨论】:

      猜你喜欢
      • 2020-02-08
      • 2021-08-17
      • 1970-01-01
      • 2020-08-30
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2021-02-06
      相关资源
      最近更新 更多