Flutter项目pubspec.yaml报错:无法插入图片,Pub get失败求助
Hey there, let's work through these problems one by one—your main issue is a syntax mistake in pubspec.yaml that's causing the pub get failure and preventing your asset image from loading.
1. The Root Cause: Incorrect Assets Format in pubspec.yaml
The error message clearly says: "Expected 'assets' to be a list, but got images/ (String)"—this is because you've assigned a single string to the assets field, but Flutter requires it to be a list of strings (each asset path on its own line prefixed with -).
Here's your corrected pubspec.yaml code:
name: mi_card_flutter description: A new Flutter application. # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # Read more about versioning at semver.org. version: 1.0.0+1 environment: sdk: ">=2.1.0 <3.0.0" dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true assets: - images/khushi.jpg
Notice the change: assets: now has an indented - images/khushi.jpg below it, which properly defines the asset as an item in a list.
2. Fixing Pub Get & Image Loading
Once you've updated the pubspec:
- Run
flutter pub getin your terminal (or click the "Pub get" button in your IDE) to refresh dependencies and register the asset. - Double-check that your image file is actually located at
project_root/images/khushi.jpg—folder names and file spelling are case-sensitive on some platforms, so make sure they match exactly. - When using
AssetImagein your code, reference the path exactly as it appears in the pubspec:AssetImage('images/khushi.jpg')
3. Verify the Fix
After making these changes, restart your Flutter app (a hot reload might not fully pick up pubspec changes) and your image should load correctly, with no more pubspec errors.
内容的提问来源于stack exchange,提问作者Khushi Zawar

