我正在开发一款Flutter应用。我一天中有很多次,我想在任何时候显示警报通知,如果正在运行,还要更改应用程序的用户界面。
所以我寻找了可以选择的选项,因此发现了以下内容
我的问题是:
PS:目前,我们对至少适用于Android的解决方案感兴趣。
我认为您仅需要后台任务即可显示通知。使用flutter_local_notifications应该足以完成您的任务。您可以使用此插件安排特定日期时间的通知。在应用程序内部,您可以使用Timer在特定日期时间触发。我给你看一个简单的例子:
class _HomePageState extends State<HomePage> {
FlutterLocalNotificationsPlugin notifPlugin;
@override
void initState() {
super.initState();
notifPlugin = FlutterLocalNotificationsPlugin();
}
Future<void> scheduleNotification(DateTime dateTime, String title) async {
final now = DateTime.now();
if (dateTime.isBefore(now)) {
// dateTime is past
return;
}
final difference = dateTime.difference(now);
Timer(difference, () {
showDialog(
context: this.context,
builder: (context) {
return AlertDialog(
content: Text(title),
);
}
);
});
await notifPlugin.schedule(title.hashCode, title, title, dateTime, platformChannelSpecifics, payload: 'test');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SafeArea(
child: Container()
),
floatingActionButton: Builder(
builder: (context) {
return FloatingActionButton(
onPressed: () {
final snackbar = SnackBar(content: Text('planned notification'), duration: Duration(seconds: 3));
Scaffold.of(context).showSnackBar(snackbar);
scheduleNotification(DateTime.now().add(Duration(seconds: 2)), 'Hello');
},
);
}
),
);
}
}
但是如果您需要进行一些计算或数据提取,那么background_fetch是您所需要的。唯一的问题是在大多数情况下,Apple不允许后台任务。