(i18n)我从MyApp类外部使用setState更改语言,收到此警告,但不知道如何解决。
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;
});
}
}
答案 0 :(得分:2)
警告信息非常清楚:函数setState
仅应从该类中调用,而不是从另一个类中调用。
解决方法很简单,在您的State
类中编写一个帮助函数,该函数为您调用setState
。例如:
refresh() => setState(() {});
现在,您可以从此类之外的地方致电state.refresh()
。
(但是,实际上,如果您正在从另一个类中调用setState
,也许您应该研究ValueNotifier
或StreamBuilder
等)