dart 无法加载Flutter中抛出的图像资源异常

jjhzyzn0  于 2023-09-28  发布在  Flutter
关注(0)|答案(6)|浏览(130)

下面是我的代码:

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
      backgroundColor: Colors.blueGrey,
      appBar: AppBar(
        title: Text('I AM RICH'),
        backgroundColor: Colors.blueGrey[900],
      ),
      body: Center(
        child: Image(
          image: AssetImage('images/diamond.png'),
        ),
      ),
    ),
    ),
  );
}

这是我得到的例外。
我的pubspec.yaml文件遵循了正确的缩进。

======= Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: images/diamond.png

When the exception was thrown, this was the stack: 
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:224:7)
<asynchronous suspension>
#1      AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:672:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "images/diamond.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#a2375(), name: "images/diamond.png", scale: 1.0)
====================================================================================================
lokaqttq

lokaqttq1#

我假设您的图像位于assets文件夹下。所以,你需要像这样调用image:

AssetImage('assets/images/diamond.png')

请确保您在pubspec.yaml中正确编写了以下内容:

assets:
  - assets/images/
7gcisfzg

7gcisfzg2#

pubspec.yaml文件中进行更改
添加这一行导入所有文件目前在images文件夹

assets:
    - images/

对于显示图像,您可以使用下面显示的任何一个代码

Image(image: AssetImage('images/diamond.png')),

Image.asset('images/diamond.png'),
7jmck4yq

7jmck4yq3#

在pubspec.yaml中添加资产路径为

assets:
  - images/diamond.png

也可以添加父文件夹路径

assets:
  - images/
4sup72z8

4sup72z84#

下面是我的pubspec.yaml文件:

name: i_am_rich
description: Show off your wealth.

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true
  assets:
    - images\
6za6bjd0

6za6bjd05#

最终问题是输入错误,**“images”应该是“images/"**有趣的是,即使在输入错误之后,pub get也会以0的退出代码执行。

bfnvny8b

bfnvny8b6#

我也遇到了同样的问题,停止并重新启动我的应用程序对我很有效

相关问题