You need to enable JavaScript to run this app. 如何通过Method Channel将List<Model>数据从Android原生端回传到Flutter端
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Method Channel将List<Model>数据从Android原生端回传到Flutter端

问题原因

Flutter Method Channel 默认使用的 StandardMessageCodec 仅支持序列化基础类型数据,Android端支持的可传输类型包含:null、Boolean、Integer、Long、Float、Double、String、byte[]、int[]、long[]、float[]、double[]、List、Map。你自定义的Java AudioModel类不在支持范围内,直接传递List会触发类型不支持的报错。

解决方案

需要先在原生端将自定义对象转换为Method Channel支持的Map类型,再在Flutter端将接收的Map反向转换为Dart侧的AudioModel对象,具体修改步骤如下:

1. 修改Android原生端返回逻辑

拿到音频列表后,先把每个AudioModel转为HashMap,再返回HashMap组成的列表,修改configureFlutterEngine中的逻辑:

@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
    super.configureFlutterEngine(flutterEngine);
    new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
            .setMethodCallHandler(
                    (call, result) -> {
                        if (call.method.equals("getMusicInfo")) {
                            List<AudioModel> tempAudioList = getMusicInfo();
                            Log.e("temp list",tempAudioList.size()+"");
                            if (!tempAudioList.isEmpty()) {
                                // 新增转换逻辑:自定义对象转Map列表
                                List<HashMap<String, String>> audioMapList = new ArrayList<>();
                                for (AudioModel model : tempAudioList) {
                                    HashMap<String, String> audioMap = new HashMap<>();
                                    audioMap.put("title", model.getTitle());
                                    audioMap.put("path", model.getPath());
                                    audioMap.put("album", model.getAlbum());
                                    audioMap.put("artist", model.getArtist());
                                    audioMapList.add(audioMap);
                                }
                                result.success(audioMapList);
                            } else {
                                result.error("UNAVAILABLE", "Current music information not available.", null);
                            }
                        } else {
                            result.notImplemented();
                        }
                    }
            );
}

2. 修改Flutter端解析逻辑

首先给Dart侧的AudioModel新增fromMap构造方法,用于将Map转换为AudioModel实例:

class AudioModel {
  final String title;
  final String path;
  final String album;
  final String artist;

  AudioModel({
    required this.title,
    required this.path,
    required this.album,
    required this.artist,
  });

  // 新增Map转对象构造方法
  factory AudioModel.fromMap(Map<String, dynamic> map) {
    return AudioModel(
      title: map['title'] as String,
      path: map['path'] as String,
      album: map['album'] as String,
      artist: map['artist'] as String,
    );
  }
}

再修改_getMusicInfo方法,对接收到的Map列表做遍历转换:

static const platform = MethodChannel('com.flover.yani_music_java/get_music_list');
Future<List<AudioModel>> _getMusicInfo() async {
  List<AudioModel> audioList = [];
  try {
    // 接收原生返回的Map列表
    final List<dynamic> rawList = await platform.invokeMethod('getMusicInfo');
    // 批量转换为AudioModel实例
    audioList = rawList.map((item) => AudioModel.fromMap(item as Map<String, dynamic>)).toList();
  } on PlatformException catch (e) {
    print('error message is $e');
  }

  print('audio list size: ${audioList.length}');
  return audioList;
}
注意事项
  • 原生端Map的key必须和Flutter端fromMap中取值的key完全一致,区分大小写
  • 如果包含非String类型字段,需要确保两端类型匹配,比如整型的音频时长需要在原生端存为Integer类型,Flutter端按int类型解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 17:39:00