首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >颤栗:简单的通知不起作用?

颤栗:简单的通知不起作用?
EN

Stack Overflow用户
提问于 2022-08-15 09:34:49
回答 1查看 62关注 0票数 0

大家好,我正在学习颤音,现在我遇到了问题,通知没有弹出。

Main.dart在这里添加了三个按钮,当单击简单通知按钮时。通知不会弹出。

代码语言:javascript
运行
复制
import 'dart:ui';    
import 'package:flutter/material.dart';
import 'package:push_notification/api/notification_api.dart';
import 'package:push_notification/util/SizeConfig.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Notification',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.start,
          children:  <Widget>[
            Icon(
              Icons.android,
              size: 80.0,
              color: Colors.lightGreen,
            ),
            SizedBox(height: 20,),
            Text(
              'Notification',
              style: const TextStyle(fontWeight: FontWeight.bold,fontSize: 50,color: Colors.black26),
            ),
            SizedBox(height: 20,),
  /*          buildButton(
              title:"Simple Notification",
              icon:Icons.notifications,
              onClicked:()=>NotificationApi.notificationDetails,
            ),*/
            RaisedButton(
              child: Text('Simple Notification'),
              onPressed: () => NotificationApi.showNotification(title: "john",body: "just eat some snacks"),
            ),
            SizedBox(height: 20,),
            buildButton(
                title:"Schedule Notification",
                icon:Icons.notifications,
                onClicked:(){}
            ),
            SizedBox(height: 20,),
            buildButton(
                title:"Remove Notification",
                icon:Icons.notifications,
                onClicked:(){}
            ),
          ],
        ),
      ),
     // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Widget buildButton({required String title, required IconData icon, required  Function()
  onClicked}) {
     return RaisedButton(
       onPressed: () {onClicked;},
       color: Color.fromRGBO(0, 0, 0, 10.0),
       child: Padding(
         padding: EdgeInsets.fromLTRB(
             SizeConfig.blockSizeHorizontal * 5,
             0,
             SizeConfig.blockSizeHorizontal * 5,
             0),
         child: Row(
           mainAxisAlignment: MainAxisAlignment.spaceBetween,
           children: <Widget>[
             Text(
               title,
               style: TextStyle(
                 fontSize: 20,
                 fontWeight: FontWeight.w700,
                 color: Colors.white,
               ),
             ),
             Icon(
               icon,
               color: Colors.white,
             )
           ],
         ),
       ),
     );
  }
}

notificationapi.dart

我使用通知颤振本地通知来显示通知。

代码语言:javascript
运行
复制
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationApi {
  static final _notification = FlutterLocalNotificationsPlugin();

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

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

}

控制台日志它显示为null

代码语言:javascript
运行
复制
 V/AutofillManager(17133): requestHideFillUi(null): anchor = null
    D/CompatibilityChangeReporter(17133): Compat change id reported: 160794467; UID 10002; state: ENABLED
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133): Failed to handle method call
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:312)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:219)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1017)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1358)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1234)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:296)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.java:320)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$TsixYUB5E6FpKhMtCSQVHKE89gQ.run(Unknown Source:12)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at android.os.Handler.handleCallback(Handler.java:938)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at android.os.Handler.dispatchMessage(Handler.java:99)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at android.os.Looper.loopOnce(Looper.java:233)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at android.os.Looper.loop(Looper.java:344)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at android.app.ActivityThread.main(ActivityThread.java:8223)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at java.lang.reflect.Method.invoke(Native Method)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
    E/MethodChannel#dexterous.com/flutter/local_notifications(17133):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)
    E/flutter (17133): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null, java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
    E/flutter (17133):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:312)
    E/flutter (17133):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:219)
    E/flutter (17133):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1017)
    E/flutter (17133):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1358)
    E/flutter (17133):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1234)
    E/flutter (17133):  at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
    E/flutter (17133):  at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:296)
    E/flutter (17133):  at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.java:320)
    E/flutter (17133):  at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$TsixYUB5E6FpKhMtCSQVHKE89gQ.run(Unknown Source:12)
    E/flutter (17133):  at android.os.Handler.handleCallback(Handler.java:938)
    E/flutter (17133):  at android.os.Handler.dispatchMessage(Handler.java:99)
    E/flutter (17133):  at android.os.Looper.loopOnce(Looper.java:233)
    E/flutter (17133):  at android.os.Looper.loop(Looper.java:344)
    E/flutter (17133):  at android.app.ActivityThread.main(ActivityThread.java:8223)
    E/flutter (17133):  at java.lang.reflect.Method.invoke(Native Method)
    E/flutter (17133):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
    E/flutter (17133):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)
    E/flutter (17133): )
    E/flutter (17133): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
    E/flutter (17133): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:177:18)
    E/flutter (17133): <asynchronous suspension>
    E/flutter (17133): #2      FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:215:7)
    E/flutter (17133): <asynchronous suspension>
    E/flutter (17133): 
    E/BLASTBufferQueue(17133): [SurfaceView[com.example.push_notification/com.example.push_notification.MainActivity]#1](f:0,a:2) isEGL=1, mPendingRelease.size()=1, mMaxAcquiredBuffers=4, currentMaxAcquiredBufferCount=2
    E/BLASTBufferQueue(17133): [SurfaceView[com.example.push_notification/com.example.push_notification.MainActivity]#1](f:0,a:3) isEGL=1, mPendingRelease.size()=2, mMaxAcquiredBuffers=4, currentMaxAcquiredBufferCount=2
EN

回答 1

Stack Overflow用户

发布于 2022-08-15 10:17:59

您必须像这样为AndroidNotificationDetails定义图标:

代码语言:javascript
运行
复制
  static Future notificationDetails() async{
    return const NotificationDetails(
      android: AndroidNotificationDetails(
        'channel id',
        'channel name',
        channelDescription: 'channel description',
        importance: Importance.max,
        icon: "ic_launcher",
      ),
      iOS: IOSNotificationDetails(),
    );
  }

并确保在此路径中的可绘制文件夹中有一个名为"ic_launcher“的图像文件:

代码语言:javascript
运行
复制
android/app/src/main/res/drawable

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73359169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档