【问题标题】:How to show local string in StatefulWidget?如何在 StatefulWidget 中显示本地字符串?
【发布时间】:2018-12-10 13:21:18
【问题描述】:

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

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

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

带有一个 const 字符串,例如:

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", "")
      ),
    );
  }
}

【问题讨论】:

  • 使用 widget.title

标签: internationalization dart flutter statefulwidget


【解决方案1】:

您使用的context 没有MaterialApp 作为父级。相反,它有一个MaterialApp 作为一个孩子。

问题是,您尝试使用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(...);
    }
  )
)

【讨论】:

  • 感谢您的帮助。今天早上我用你的方法尝试了同样的方法,终于成功了。
  • 此解决方案在 2020 年仍然可用。不幸的是,大多数编写的教程/视频仅基于 Stateless 小部件,这些小部件在 Statefull 小部件旁边具有不同类型的上下文
  • 这对我也有用,除了我的是 StatelessWidget
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多