在 Flutter 和 Dart 中找不到资产

问题描述 投票:0回答:6

我在尝试运行我的应用程序时遇到“找不到资产”错误。这是我的文件。

main.dart:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('I Am Rich'),
        centerTitle: true,
        backgroundColor: Colors.blueGrey[900],
      ),
      // You can also
      body: Center(child: Image(image: AssetImage("images/poor.png"))),
      backgroundColor: Colors.blueGrey,
    ),
    debugShowCheckedModeBanner: false,
  ));
}

pubspec.yaml:

name: i_am_poor
description: A new Flutter project.
version: 1.0.0+1


environment:
  sdk: '>=2.19.6 <3.0.0'

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^2.0.0
flutter:
  assets:
    - images/poor.png

文件结构: file structure

我尝试了什么:我尝试查看文档并直接从那里复制粘贴,同时根据我的情况进行调整。

flutter dart assets
6个回答
1
投票

将破折号向后移动以与

assets
这个词对齐,如下所示:

flutter:
  assets:
  - images/

此外,您无需在

poor.png
中指定
pubspec.yaml
,只需文件夹名称即可访问其中的所有图像。

您的结构不在 lib 中。但对于其他人:仔细检查您的资产文件夹是否不在 lib 中,因为如果是,您需要添加它:

flutter:
  assets:
  - lib/images/

0
投票

你还需要包括资产目录

试试这个 AssetImage("assets/images/poor.png")


0
投票

用这种方式代替。

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('I Am Rich'),
        centerTitle: true,
        backgroundColor: Colors.blueGrey[900],
      ),
      // You can also
      body: Center(
      child: Image.Asset("images/poor.png"),
      backgroundColor: Colors.blueGrey,
    ),
    debugShowCheckedModeBanner: false,
  ));
}

0
投票

问题可能出在你的 pubspec.yaml 文件中。 删除不必要的空格并再次执行

pubspec.yaml

flutter:
  assets:
    - images/poor.png

0
投票

您应该按照以下步骤将图像目录添加到资产中。确保保持正确的模式和格式,因为不必要的空格可能是一个问题。确保在更新

pubspec.yaml

后做一个 pub get
# The following section is specific to Flutter packages.
flutter:
  assets:
    - images/

请注意,我们不必指定

poor.png
,因为添加目录就足够了。


0
投票

第一步:点击复制图像的相对路径
第 2 步: 在代码中复制该路径,如

AssetImage("<your_image_path>")
Image.asset("<your_image_path>")

另一种方式:lib文件夹外创建assets文件夹,并在pubspec.yaml内设置

assets
文件夹的路径。 像这样pubspec.yaml screenshot。然后按照上面的步骤。

© www.soinside.com 2019 - 2024. All rights reserved.