我在根实例上写了监听代码appModel!.addListener,在一个子页面中进行触发notifyListeners的操作,但addListener中的函数并未执行,为什么呀?
代码如下:
根页面
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
AppModel? appModel;
@override
void initState() {
super.initState();
Future.delayed(Duration.zero, () {
appModel = Provider.of<AppModel>(context, listen: false);
appModel!.addListener(() {
print("change ${appModel!.localeCode}");//并未触发
});
});
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
GlobalProperty.appContext = context;
// print(ChinaDataArea.data);
// print("asd:");
// print(ChinaDataArea.codeToText("710110"));
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: MConfig.NAME,
theme: themeData,
home: const SplashPage(),
// home: const TabPage(),
// routes: MRouter.routes,
getPages: Pages.pages,
navigatorKey: GlobalProperty.navigatorKey,
locale: Locale(appModel == null ? "en" : appModel!.localeCode),
appModel
class AppModel with ChangeNotifier {
IndexSetting indexSetting = IndexSetting();
String localeCode = 'en';
Future init() async {
await LocalStorage.getItem('indexSetting').then((value) {
setIndexSetting(value);
});
await LocalStorage.getItem('localeCode').then((value) {
if (value != null) {
setLocale(value);
}
});
}
setIndexSetting(data) {
if (data == null) {
indexSetting = IndexSetting();
LocalStorage.remove("indexSetting");
} else {
indexSetting = IndexSetting.fromJson(data);
LocalStorage.setItem("indexSetting", indexSetting);
}
notifyListeners(); //
}
setLocale(String code) {
localeCode = code;
LocalStorage.setItem("localeCode", code);
notifyListeners(); //
}
}
子页面
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("中文"),
Radio(
value: 1,
groupValue: radio,
activeColor: ColorConst.primaryColor,
onChanged: (value) {
radio = 1;
appModel?.setLocale("zh");
setState(() {});
}),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("English"),
Radio(
value: 2,
groupValue: radio,
activeColor: ColorConst.primaryColor,
onChanged: (value) {
radio = 2;
appModel?.setLocale("en");
setState(() {});
}),
],
)