我无法根据用户选择的时间显示每日本地通知。
要查看我是否忘记了任何权限,我尝试实现一个按钮以立即显示本地通知,并且可以正常工作。
如果安排了通知,则此代码可确保在页面加载时显示
class _LocalNotificationWidgetState extends State<LocalNotificationWidget> {
final notifications = FlutterLocalNotificationsPlugin();
Time timePickedtime;
TimeOfDay _time = TimeOfDay.now();
TimeOfDay picked;
var timeText;
bool showReminder;
String remindTime;
@override
void initState() {
getReminderTime().then((result) {
setState(() {
result != null ? timeText = result : timeText = '00:00';
});
});
getReminder().then((result) {
setState(() {
showReminder = result;
});
});
super.initState();
}
构建时间选择器小部件
Widget _buildTimePicker() {
return GestureDetector(
onTap: () async {
await _showDailyAtTime(context);
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
color: Colors.white),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
timeText != null ? timeText.toString() : '00:00',
style: TextStyle(fontSize: 50.0, fontWeight: FontWeight.w200),
),
Switch(
value: showReminder == null ? false : showReminder,
onChanged: (bool value) {
setState(() {
showReminder = value;
setReminder(value);
});
},
),
],
),
),
);
}
调度方法
Future<Null> _showDailyAtTime(BuildContext context) async {
picked = await showTimePicker(context: context, initialTime: _time);
if (picked != null && picked != _time) {
setState(() {
_time = picked;
});
}
if (picked != null) {
timePickedtime = Time(picked.hour, picked.minute, 0);
}
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'repeatDailyAtTime channel id',
'repeatDailyAtTime channel name',
'repeatDailyAtTime description');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
setState(() {
timeText =
'${_toTwoDigitString(picked.hour)}:${_toTwoDigitString(picked.minute)}';
setReminderTime(timeText);
});
if (showReminder) {
await notifications.showDailyAtTime(
0,
'Reminder',
'Have you used this app today? Daily notification shown at approximately ${_toTwoDigitString(picked.hour)}:${_toTwoDigitString(picked.minute)}:',
timePickedtime,
platformChannelSpecifics);
}
}
在设备上存储时间表
Future<bool> getReminder() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool('showReminder');
}
Future<bool> setReminder(bool value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setBool('showReminder', value);
}
Future<bool> setReminderTime(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setString('timeText', value);
}
Future<String> getReminderTime() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('timeText');
}