我在尝试运行我的应用程序时遇到“找不到资产”错误。这是我的文件。
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
我尝试了什么:我尝试查看文档并直接从那里复制粘贴,同时根据我的情况进行调整。
将破折号向后移动以与
assets
这个词对齐,如下所示:
flutter:
assets:
- images/
此外,您无需在
poor.png
中指定pubspec.yaml
,只需文件夹名称即可访问其中的所有图像。
您的结构不在 lib 中。但对于其他人:仔细检查您的资产文件夹是否不在 lib 中,因为如果是,您需要添加它:
flutter:
assets:
- lib/images/
你还需要包括资产目录
试试这个 AssetImage("assets/images/poor.png")
用这种方式代替。
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,
));
}
问题可能出在你的 pubspec.yaml 文件中。 删除不必要的空格并再次执行
pubspec.yaml
flutter:
assets:
- images/poor.png
您应该按照以下步骤将图像目录添加到资产中。确保保持正确的模式和格式,因为不必要的空格可能是一个问题。确保在更新
pubspec.yaml
后做一个 pub get
# The following section is specific to Flutter packages.
flutter:
assets:
- images/
请注意,我们不必指定
poor.png
,因为添加目录就足够了。