internationalization - 如何在 StatefulWidget 中显示本地字符串?

标签 internationalization dart flutter statefulwidget

我已经学习了如何通过 StatelessWidget 使用 i18n 进行 flutter 练习, 但仍然无法通过 StatefulWidget 工作。

我可以简单地替换下面的代码

title: new Text(S.of(context).title)

使用常量字符串,例如:

title: const Text("A Test Title");

所以我认为其他一切都应该没问题。唯一的问题是 i18n 不起作用。

有人可以帮助我,“如何通过 StatefulWidget 在 flutter 上使用 i18n?”

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'generated/i18n.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  BuildContext c;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var tiles = new List<Widget>();

    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(S.of(context).title), // Here is the problem
        ),
        body: new Stack(
          children: <Widget>[
            new Container(),
            new ListView(
              children: tiles,
            )
          ],
        ),
      ),
      localizationsDelegates: [S.delegate],
      supportedLocales: S.delegate.supportedLocales,
      localeResolutionCallback: S.delegate.resolution(
          fallback: new Locale("en", "")
      ),
    );
  }
}

最佳答案

您正在使用的 context 没有 MaterialApp 作为父级。相反,它有一个 MaterialApp 作为 child 。

问题是,您尝试使用 S.of(context) 获取的 S 实例存储在 MaterialApp 中。因此错误。

您可以改为使用不同的 context,其中 context 在其父级中具有 MaterialApp

实现此目的的最简单方法是将应用的一部分包装到 Builder 中。

类似的东西:

return MaterialApp(
  home: Builder(
    builder: (context) {
      const title = S.of(context).title; // works now because the context used has a MaterialApp inside its parents
      return Scaffold(...);
    }
  )
)

关于internationalization - 如何在 StatefulWidget 中显示本地字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134053/

相关文章:

django - 搜索引擎如何看待本地化的 Django 站点?

php - 同时使用 gettext 和数据库驱动的翻译

适用于 Linux 的 Qt 嵌入式。键盘布局切换

dart - 如何在 Dart 上准备好对象时分派(dispatch)事件?

dart - Dart AOT 是如何工作的?

dart - 从请求中获取原始字节

firebase - 如何将拨动开关按钮从 flutter 添加到 firebase firestore 数据库

c++ - 如何使用 C++ 的特性来更干净地使用 i18n 库,而不是直接使用 C 的 gettext()

flutter - 在 Flutter GestureDetector 上的 DoubleTap 上获取 "details"

android - 如何从付费应用转换为应用内购买? iOS和Android + Flutter