Chi*_* Yu 1 internationalization dart flutter statefulwidget
我已经学习了如何通过 StatelessWidget 使用 i18n 进行我的颤振练习,但仍然无法通过 StatefulWidget 工作。
我可以简单地替换以下代码
title: new Text(S.of(context).title)
Run Code Online (Sandbox Code Playgroud)
使用 const 字符串,例如:
title: const Text("A Test Title");
Run Code Online (Sandbox Code Playgroud)
所以我认为其他一切都应该没问题。唯一的问题是 i18n 不起作用。
有人可以帮助我,“如何在 Flutter 上通过 StatefulWidget 使用 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", "")
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
在context你使用不具有MaterialApp作为父母。相反,它有一个MaterialApp作为一个孩子。
问题是,S您尝试使用的实例S.of(context)存储在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(...);
}
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
615 次 |
| 最近记录: |