LateInitializationError字段“_instance...”尚未使用flutter本地通知包进行初始化

yacmzcpb  于 2023-04-22  发布在  Flutter
关注(0)|答案(1)|浏览(204)

我是新的Flutter,现在我正试图实现按钮点击Android上的本地通知(与本地通知包).我尝试了不同的方法多个教程,但我最终总是得到相同的错误:
“[错误:flutter/runtime/dart_vm_initializer.cc(41)]未处理的异常:LateInitializationError:字段'_instance@...'尚未初始化。”
下面是我的服务“notification_service”代码

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationApi {
  static final _notifications = FlutterLocalNotificationsPlugin();

  static Future _notificationDetails() async {
    return NotificationDetails(
      android: AndroidNotificationDetails(
        'channel id',
        'channel name',
        'channel description',
        importance: Importance.max,
      ),
      iOS: IOSNotificationDetails(),
    );
  }

  static Future showNotification({
    int id = 0,
    String? title,
    String? body,
    String? payload,
  }) async =>
    _notifications.show(
      id,
      title,
      body,
      await _notificationDetails(),
      payload: payload
    );

}

这里是我的代码,我试图在按钮presend上实现我的通知方法:

import 'package:flutter/material.dart';
import 'package:my_goal_app/services/notification_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NewsWidget extends StatefulWidget {

  @override
  State<NewsWidget> createState() => _NewsWidgetState();
}

class _NewsWidgetState extends State<NewsWidget> {

  @override
  Widget build(BuildContext context) {
   return Scaffold(
        appBar: AppBar(
                    title: Text('News')
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () => NotificationApi.showNotification(
              title: 'What a great title',
              body: 'Hey! This is a Body!',
              payload: 'sarah.abs',
            ),
            child: Text('click me'),
          ),
        ));
        }
  }

正如我已经说过的,我在youtube上尝试了不同的教程,但遇到了同样的问题。我试图编辑AndroidManifest,但没有任何效果。当然,我尝试了像LateInitializationError: Field 'data' has not been initialized, got errorthis这样的解决方案
我已经在这个问题上工作了好几天了,但还是没能解决这个问题。如果有人能帮助我,我会很高兴的。如果我泄露了任何信息,请告诉我,这是我的第一篇文章。

j9per5c4

j9per5c41#

static Future _notificationDetails() async {
    return const NotificationDetails(
      android: AndroidNotificationDetails(
        'channel id',
        'channel name',
        'channel description',
        icon: 'ic_launcher',
        importance: Importance.max,
      ),
      iOS: IOSNotificationDetails(),
    );
  }

可以在drawable文件夹中添加ic_launcher,并在AndroidNotificationDetails中添加icon吗?
卸载以前的应用程序并重新安装然后运行?

相关问题