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

Flutter使用flutter_midi_command时then回调指定类型报错如何解决

解决flutter_midi_command中then回调的类型标注问题

你的问题出在对MidiCommand().devices的返回值类型判断错误:它返回的是Future<List<MidiDevice>?>(可空的MIDI设备列表的Future),而不是单个MidiDevice,所以你给then的回调参数标注单个MidiDevice才会触发类型不匹配错误。

要让带类型标注的回调正常工作,只需要把参数类型改成正确的List<MidiDevice>?即可:

ElevatedButton(
  onPressed: () => MidiCommand().devices.then((List<MidiDevice>? devices) => print(devices)),
  child: const Text('Show available MIDI devices'),
)

如果觉得链式调用的写法不够直观,也可以用async/await的方式,类型标注会更清晰:

ElevatedButton(
  onPressed: () async {
    // 显式标注变量类型
    List<MidiDevice>? devices = await MidiCommand().devices;
    print(devices);
  },
  child: const Text('Show available MIDI devices'),
)

移除类型标注后Dart会自动推断参数为List<MidiDevice>?,所以不会报错,但显式标注正确类型能让代码可读性更强,也能在编译阶段提前发现类型问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:35:16