问题描述
(i18n)我从MyApp类外部使用setState更改语言,收到此警告,但不知道如何解决.
(i18n) I use setState from outside of MyApp class to change language, I got this warning, and don't know how to solve it.
info: The member 'setState' can only be used within instance members of subclasses of 'package:flutter/src/widgets/framework.dart'. (invalid_use_of_protected_member at [flutter_firebase_authen] lib\app.dart:22)
class MyApp extends StatefulWidget {
final FirebaseAnalyticsObserver observer;
const MyApp({
Key key,
@required this.observer,
}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
static void setLocale(BuildContext context, Locale newLocale) {
final _MyAppState state = context.ancestorStateOfType(const TypeMatcher<_MyAppState>());
state.setState(() {
state.locale = newLocale;
});
}
}
推荐答案
警告消息非常清楚:函数 setState
只能从该类内部调用,而不能从另一个类调用.
The warning message is quite clear: the function setState
should only be called from within the class, not from another class.
解决方法很简单,在 State
类中编写一个帮助程序函数,该函数为您调用 setState
.例如:
The workaround is simple, write a helper function inside your State
class, that calls setState
for you. For example:
refresh() => setState(() {});
现在从此类之外,您可以调用 state.refresh()
.
Now from outside this class, you can call state.refresh()
.
(但实际上,如果您要从另一个类调用 setState
,也许您应该研究 ValueNotifier
或 StreamBuilder
等).
(But really, if you are calling setState
from another class, maybe you should look into ValueNotifier
, or StreamBuilder
, etc.)
这篇关于成员"setState"只能在"package:flutter/src/widgets/framework.dart"子类的实例成员中使用.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!