我已经学习了如何使用i18n通过StatelessWidget进行颤振练习,但仍然没有通过StatefulWidget工作。
我可以简单地替换以下代码
title: new Text(S.of(context).title)例如,使用const字符串:
title: const Text("A Test Title");所以我觉得其他的都应该没事。唯一的问题是i18n不能工作。
能帮我个忙吗,“如何通过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", "")
),
);
}
}发布于 2018-07-02 11:04:49
您使用的context没有将MaterialApp作为父级。相反,它有一个作为孩子的MaterialApp。
问题是,您试图使用S.of(context)获取的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(...);
}
)
)https://stackoverflow.com/questions/51134053
复制相似问题