【问题标题】:Cannot localize strings in Flutter TabBarView无法在 Flutter TabBarView 中本地化字符串
【发布时间】:2019-07-18 19:23:17
【问题描述】:

当我尝试在 TabBarView 中本地化字符串时,我收到此错误:

NoSuchMethodError:在 null 上调用了方法“翻译”。接收方:空。尝试调用:translate("username).

我使用这行代码将键转换为本地化字符串:

AppLocalizations.of(context).translate('username')

这在我的应用程序的所有其他屏幕上都很好用,除了这个。有谁知道为什么它不起作用以及如何解决它?

我已经尝试过的一些事情:

  • 传递主屏幕的上下文(包含所有 TabBarViews 的屏幕)

  • 将每个 ListTile 包装在 Builder 中

  • 将 ListView 包装在 Builder 中

代码:

class AccountScreen extends StatelessWidget {
  final String username;
  final String email;
  final int points;

  AccountScreen(this.username, this.email, this.points);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Padding(
        padding: EdgeInsets.all(10),
        child: ListView(
          children: <Widget>[
            ListTile(
              title: Text(AppLocalizations.of(context).translate('username')),
              subtitle: Text(username),
            ),
            ListTile(
              title:
                  Text(AppLocalizations.of(context).translate('email_address')),
              subtitle: Text(email),
            ),
            ListTile(
              title: Text(AppLocalizations.of(context).translate('points')),
              subtitle: Text('$points'),
            ),
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter localization


    【解决方案1】:

    我发现了同样的问题。但在我的情况下,使用MaterialApp 而不使用localizationsDelegates。 (我的意思是所有文件不仅仅是main.dart)。

    所以我在所有小部件的每个MaterialApp 上添加localizationsDelegates

    例如

       MaterialApp(
          localizationsDelegates: [
            MainLocalizationsDelegate.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          home: DefaultTabController(
            length: 2,
            child: Scaffold(
              appBar: AppBar(
                brightness: Brightness.light,
                bottom: TabBar(
                  tabs: [
                    Tab(text: MainLocalizations.of(context).food),
                    Tab(text: MainLocalizations.of(context).car),
                  ],
                ),
              ),
              body: TabBarView(
                children: [
                  TabA(),
                  TabB(),
                ],
              ),
            ),
          ),
        );
    

    【讨论】:

      【解决方案2】:

      问题在于应用程序内部有多个 MaterialApp 小部件,导致本地化过程出现一些冲突。删除 Redundant MaterialApp 小部件解决了该问题。

      【讨论】:

        猜你喜欢
        • 2019-06-10
        • 2019-05-01
        • 2014-03-11
        • 1970-01-01
        • 1970-01-01
        • 2010-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多