【问题标题】:How to add album arts in flutter如何在颤振中添加专辑封面
【发布时间】:2026-02-07 02:20:06
【问题描述】:

我正在使用 Flute 音乐播放器插件在 Flutter 中制作音乐播放器应用程序。但我无法添加专辑封面。

我写道:

  dynamic getImage(int idx) {
      return _songs[idx].albumArt == null
      ? null
      : new File.fromUri(Uri.parse(_songs[idx].albumArt));
  }

我使用了 Image.file 小部件:

Container(
    childe: Image.file(getImage(_index))
)

结果是:

I/flutter (15576): The following assertion was thrown building HyperMusicHome(dirty, state:
I/flutter (15576): _HyperMusicHomeState#b83f2):
I/flutter (15576): 'package:flutter/src/painting/image_provider.dart': Failed assertion: line 621 pos 14: 'file !=
I/flutter (15576): null': is not true.
I/flutter (15576):
I/flutter (15576): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter (15576): more information in this error message to help you determine and fix the underlying cause.
I/flutter (15576): In either case, please report this assertion by filing a bug on GitHub:
I/flutter (15576):   https://github.com/flutter/flutter/issues/new?template=BUG.md

【问题讨论】:

  • 我编辑并添加了错误信息

标签: flutter


【解决方案1】:

您收到的错误来自 Flutter 的 FileImage 类中的 this line,该类检查您传递给 Image.file() 的内容是否为 null。您当前正在观看的歌曲似乎没有专辑封面。您需要做的就是在没有专辑封面时不显示图像。

我不知道你的小部件到底长什么样,但你可以这样做:

@override
Widget build(BuildContext context) {
  // Call `getImage` once to get the image file (which might be `null`)
  final albumArtFile = getImage(_index);

  return Container(
    // Only show the image if `albumArtFile` is not `null`
    child: albumArtFile != null ? Image.file(albumArtFile) : null,
  );
}

您还可以将占位符图像与您的应用捆绑在一起,并在没有专辑封面时显示:

albumArtFile != null ? Image.file(albumArtFile) : Image.asset('assets/placeholder.png')

您可以通过here了解更多关于向您的应用添加资产的信息。

【讨论】:

  • 哦。我选择了没有专辑封面图像的文件。我试过调试,它说'albumArt:null'。谢谢你的回答。
  • 没问题!不要忘记接受我的回答(点击✓)。
  • 我刚刚添加了有专辑封面的音乐。其他音乐应用程序显示专辑封面,但调试器仍然显示“albumArt:null”。我认为这是插件的问题。你怎么看?
  • 是的,它可能是。该插件似乎试图在特定文件夹中查找专辑封面,而不是查看图片embedded within the audio files themselves