ユーザーがsharedPreferencesに保存し、URLに追加して呼び出しを行うパラメーターに基づいて通知を送信しようとしています。savedCity を作成すると通知が機能しますが、sharedPreferences から取得しようとすると失敗します。どうすればこれを機能させることができますか?
void callbackDispatcher() {
Workmanager.executeTask((task, inputData) async {
String savedCity = "";
// final prefs = await SharedPreferences.getInstance();
// savedCity = prefs.getString('defaultCity') ?? "";
if (task == 'uniqueKey') {
var response = await http.get(Uri.parse('http://api.openweathermap.org/data/2.5/weather?q=$savedCity&units=metric&appid=$API_KEY'));
Weather dataComingFromTheServer = Weather.fromJson(json.decode(response.body));
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('your channel id', 'your channel name',
'your channel description',
importance: Importance.max,
priority: Priority.high,
showWhen: false);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
dataComingFromTheServer.name,
'${dataComingFromTheServer.weather[0].description} ${dataComingFromTheServer.main.tempMin}ºC - ${dataComingFromTheServer.main.tempMax}ºC',
platformChannelSpecifics,
payload: 'item x');
}
return Future.value(true);
});
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings(
'@mipmap/ic_launcher');
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings();
final MacOSInitializationSettings initializationSettingsMacOS =
MacOSInitializationSettings();
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
macOS: initializationSettingsMacOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: selectNotification);
Workmanager.initialize(
callbackDispatcher,
isInDebugMode:
true);
Workmanager.registerPeriodicTask(
"1",
"uniqueKey",
frequency: Duration(minutes: 15),
);
runApp(MyApp());
}
void setPreference(String cityName) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString('defaultCity', cityName);
}