如何解决Flutter:来自后台任务的通知导航,没有上下文问题
我的应用程序执行以下操作:它使用 Flutter Workmanager 运行后台任务,该任务检查一些值,然后通过 Flutter 本地通知抛出通知。在 Flutterlocalnotifications 插件的 initialize 方法中,我可以指定一个内联函数,它应该导航到一个页面。由于我没有 Builder 上下文,因此我必须使用带有 OnGenerateRoute 的 Navigator Key 将用户转发到站点。但是,这不起作用,我不知道为什么。我知道当应用程序被杀死时,此代码很有用。
示例代码
final NotificationApplaunchdetails? notificationApplaunchdetails =
await FlutterlocalnotificationsPlugin.getNotificationApplaunchdetails();
String initialRoute = HomePage.routeName;
if (notificationApplaunchdetails?.didNotificationLaunchApp ?? false) {
selectednotificationPayload = notificationApplaunchdetails!.payload;
initialRoute = SecondPage.routeName;
}
但是当应用程序还活着时该怎么办?下面列出了我的项目代码。
Main.Dart
void main() {
WidgetsFlutterBinding.ensureInitialized();
Workmanager().initialize(callbackdispatcher,isInDebugMode: true);
Workmanager().registerPeriodicTask("1","test",frequency: Duration(minutes: 15));
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',theme: ThemeData(
primarySwatch: Colors.blue,),initialRoute: "/",navigatorKey: NavigationService.navigatorKey,onGenerateRoute: RouteGenerator.generateRoute
);
}
}
RouteGenerator.dart
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
switch(settings.name) {
case '/first':
return MaterialPageRoute(builder: (_) => Page1(title: "First"));
case '/second':
return MaterialPageRoute(builder: (_) => Page2(title: "Second"));
case '/third':
return MaterialPageRoute(builder: (_) => Page3(title: "Third"));
case '/fourth':
return MaterialPageRoute(builder: (_) => Page4(title: "Fourth"));
}
return MaterialPageRoute(builder: (_) => Page0(title: "Root!"));
}
}
class NavigationService {
static final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
static Future<dynamic> navigateto(String routeName) {
return navigatorKey.currentState!.pushNamed(routeName);
}
}
service.dart
class DevHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext? context) {
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert,String host,int port) => true;
}
}
void callbackdispatcher() {
Workmanager().executeTask((task,inputData) async{
HttpOverrides.global = new DevHttpOverrides();
var url = 'https://172.16.0.100/handler.PHP?page=settings';
http.Response response = await http.get(Uri.parse(url));
List<dynamic> list = jsonDecode(response.body);
SharedPreferences prefs = await SharedPreferences.getInstance();
var usage = "Beides";
var checkValue = "temp_out";
var borderValueString = "14.9";
var checktype = "Grenzwert überschreiten";
var borderValueDouble;
var message = "";
if(usage != "Nur Home Widgets" && checkValue != "" && borderValueString != "" && checktype != "")
{
var value = list[0][checkValue];
if (double.tryParse(borderValueString) != null && double.tryParse(value) != null)
{
borderValueDouble = double.parse(borderValueString);
value = double.parse(value);
}
if (checktype == "Grenzwert unterschreiten")
{
if (borderValueDouble is double)
{
if (value <= borderValueDouble)
{
message = "Grenzwert unterschritten";
}
}
}
else if (checktype == "Grenzwert überschreiten")
{
if (borderValueDouble is double)
{
if (value >= borderValueDouble)
{
message = "Grenzwert überschritten";
}
}
}
else if (checktype == "Entspricht Grenzwert")
{
if (borderValueDouble == value)
{
message = "Grenzwert erreicht";
}
}
}
if(message != "")
{
FlutterlocalnotificationsPlugin flip = new FlutterlocalnotificationsPlugin();
var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
var ios = new IOSInitializationSettings();
var settings = new InitializationSettings(android: android,iOS: ios);
flip.initialize(settings,onSelectNotification: (String? payload) async {
await NavigationService.navigatorKey.currentState!.push(MaterialPageRoute(builder: (context) => Page4(title: "Hello")));
});
var androidplatformChannelSpecifics = new AndroidNotificationDetails(
'1','weatherstation','Notify when values change',importance: Importance.max,priority: Priority.high
);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(
android: androidplatformChannelSpecifics,iOS: iOSPlatformChannelSpecifics);
await flip.show(0,message,'App öffnen für weitere Details',platformChannelSpecifics,payload: 'Default_Sound'
);
}
return Future.value(true);
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。