You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter本地通知在Android模拟器及真机均不显示且报错求助

Flutter Android本地通知触发StandardMethodCodec报错解决方案

问题描述

我在Android平台用Flutter SDK实现本地通知,找了个简易示例(含main.dart和noti.dart,点击按钮触发通知),但点击按钮时出现StandardMethodCodec相关报错,在Pixel 5 API 30模拟器和Android 11(MIUI 12.5.14)真机上都没法正常显示通知,已经在app build.gradle里设置compileSdkVersion 33,不知道怎么解决。

代码片段

main.dart代码

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:webserver/noti.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState(){
    super.initState();
    Noti.initialize(flutterLocalNotificationsPlugin);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [Color(0xFF3ac3cb), Color(0xFFf85187)])),
      child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            backgroundColor: Colors.blue.withOpacity(0.5),

          ),
          body: Center(
            child: Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20)
              ),
              width: 200,
              height: 80,
              child: ElevatedButton(
                onPressed: (){
                  Noti.showBigTextNotification(title: "New message title", body: "Your long body", fln: flutterLocalNotificationsPlugin);
                }, child: Text("click"),
              ),
            ),
          )),
    );
  }
}

noti.dart代码

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class Noti{
  static Future initialize(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
    var androidInitialize = const AndroidInitializationSettings('mipmap/ic_launcher');
    var iOSInitialize = const IOSInitializationSettings();
    var initializationsSettings = InitializationSettings(android: androidInitialize,
        iOS: iOSInitialize);
    await flutterLocalNotificationsPlugin.initialize(initializationsSettings );
  }

  static Future showBigTextNotification({var id =0,required String title, required String body,
    var payload, required FlutterLocalNotificationsPlugin fln
  } ) async {
    AndroidNotificationDetails androidPlatformChannelSpecifics =
    const AndroidNotificationDetails(
      'you_can_name_it_whatever1',
      'channel_name',

      playSound: true,
      sound: RawResourceAndroidNotificationSound('notification'),
      importance: Importance.max,
      priority: Priority.high,
    );

    var not= NotificationDetails(android: androidPlatformChannelSpecifics,
        iOS: const IOSNotificationDetails()
    );
    await fln.show(0, title, body,not );
  }
}

报错信息

E/flutter ( 2807): #0 StandardMethodCodec.decodeEnvelope
(package:flutter/src/services/message_codecs.dart:653:7) E/flutter (
2807): #1 MethodChannel._invokeMethod
(package:flutter/src/services/platform_channel.dart:296:18) E/flutter
( 2807): E/flutter ( 2807): #2
FlutterLocalNotificationsPlugin.show
(package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:215:7)
E/flutter ( 2807): E/flutter ( 2807): #3
Noti.showBigTextNotification (package:webserver/noti.dart:29:5)
E/flutter ( 2807): E/flutter ( 2807):

解决方案

  • 检查通知音频资源:代码里指定了RawResourceAndroidNotificationSound('notification'),要确保Android项目的res/raw目录下存在全小写的notification音频文件(格式支持mp3、wav等)。如果没有这个文件,要么添加资源,要么删除sound参数改用系统默认通知音。
  • 等待初始化完成:initState里调用的初始化方法是异步的,直接调用会导致插件未初始化完成就触发通知,修改成以下方式:
    @override
    void initState() {
      super.initState();
      _initNotifications();
    }
    
    Future<void> _initNotifications() async {
      await Noti.initialize(flutterLocalNotificationsPlugin);
    }
    
  • 补充频道描述参数:新版本flutter_local_notifications要求AndroidNotificationDetails必须传入channelDescription,补充该参数:
    AndroidNotificationDetails androidPlatformChannelSpecifics =
    const AndroidNotificationDetails(
      'you_can_name_it_whatever1',
      'channel_name',
      channelDescription: '消息通知频道', // 新增这一行
      playSound: true,
      sound: RawResourceAndroidNotificationSound('notification'),
      importance: Importance.max,
      priority: Priority.high,
    );
    
  • 更新插件版本:旧版本插件和高版本Android SDK可能存在兼容性问题,打开pubspec.yaml将flutter_local_notifications更新到最新稳定版,执行flutter pub get后重新运行。
  • 添加权限声明:在AndroidManifest.xml中添加通知权限,即使Android 11默认授予,声明后更稳妥:
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    
  • 清理重建项目:执行flutter clean清除缓存,再执行flutter pub get,最后重新编译运行项目。

内容的提问来源于stack exchange,提问作者BrainTrance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:55:20