cronStock() async {
_stockCode = _stockCodeController.value.text;
_growRate = _growRateController.value.text;
_reduceRate = _reduceRateController.value.text;
……
saveData();
refreshStock(true);
await AndroidAlarmManager.periodic(const Duration(seconds: 30), periodicAlarmID, refreshStock, wakeup: true);
}
saveData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.reload();
try {
print('0001 saveData: '+DateTime.now().toString());
prefs.setString('stock_prefix', stockPrefix);
prefs.setString('stock_code', _stockCodeController.value.text);
prefs.setDouble('grow_rate', double.parse(_growRateController.value.text));
prefs.setDouble('reduce_rate', double.parse(_reduceRateController.value.text));
} on FormatException catch(e) {
} catch (e) {
// No specified type, handles all
}
}
……
refreshStock([bool isManual = false]) {
print('0002 refreshStock afterTimer: '+DateTime.now().toString());
Future<List> stockShared = getShared();
stockShared.then((List shared) {
print('isManual: $isManual');
print('shareData: $shared');
});
}
Future<List> getShared() async {
print('getShared');
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.reload();
return [
prefs.getString('stock_prefix'),
prefs.getString('stock_name'),
prefs.getString('stock_code'),
prefs.getDouble('grow_rate'),
prefs.getDouble('reduce_rate'),
// 当前值
prefs.getString('stock_price'),
prefs.getDouble('stock_rate'),
prefs.getInt('rate_color'),
];
}
AndroidAlarmManager 插件用到了 Isolate 环境,在 Isolate 环境下 refreshStock 函数中的 getShared()拿到的 SharedPreferences 数和上面 saveData()存储的数据不同步,要多次间隔调用的后才会同步到。