无法加载资产:assets/image1 (Flutter)

Unable to load asset: assets/image1 (Flutter)

几天前我遇到了这个问题,我不知道怎么解决的,但我设法解决了。我仍然不知道究竟是什么原因造成的。每当我创建一个新的 flutter 项目并尝试在我的应用程序中添加资产图像时,它都会抛出此错误:

======== Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: assets/image01

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: "assets/image01")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#abc8a(), name: "assets/image01", scale: 1.0)
====================================================================================================

我浏览了一段时间以找到解决方案,但找不到解决方案,有时我只是重新启动应用程序并 运行 '''flutter clean''' 修复它,但它不是'这次不工作。我不知道该怎么做,pubsec.yaml 和代码似乎工作正常。我试过创建新项目并重建 gradle 但效果不佳。请提供描述性和有用的答案。

代码如下:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Center(
                child: CircleAvatar(
                  radius: 100,
                  backgroundColor: Colors.blue,
                  child: Image.asset('assets/image01'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这里是 pubsec.yaml

name: mi_card
description: A new Flutter project.

publish_to: 'none'

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:
    - assets/

您必须指定图像的扩展名(即 image01.png)

child: Image.asset('assets/image01.png')

试试下面的代码

在 pubspec.yaml 文件中添加以下代码。

flutter:
  assets:
    - assets/
  uses-material-design: true

并创建图像小部件,添加将您保存在任何文件夹中的图像路径,例如 assets/image.png 以及您的图像扩展名

Center(
            child: CircleAvatar(
              radius: 100,
              backgroundColor: Colors.blue,
              child: Image.asset('assets/image01.png'),
            ),
          ),
        

首先创建文件夹 - 最佳名称(图片)。把你的照片,所有你想要的照片,打电话。然后转到图片的pubspec.yml页面编辑部分。

flutter:
  uses-material-design: true //two space 
  assets:                    //same up space 
    - images/                //two speace after asset 

然后转到您的代码添加所有路径。示例:

backgroundImage: AssetImage("images/ss.jpeg"),