成员'setState'只能在 'package:flutter/src/widgets/framework.dart' 的子类的实例成员中使用



(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] libapp.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只能从类内调用,而不能从其他类调用。

解决方法很简单,在State类中编写一个助手函数,为您调用setState。例如:

refresh() => setState(() {});

现在,从这个类之外,您可以调用state.refresh()

(但实际上,如果您从另一个类调用setState,也许您应该研究ValueNotifierStreamBuilder等。(

最新更新