Steps to Reproduce
- Create a flutter app.
- Modify pubspec.yaml for adding some vendors:
name: alfraid
description: Something I need
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.0
flutter_swiper: ^1.0.2
carousel: ^0.1.0
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- images/icons/today.png
- images/icons/today_on.png
- images/icons/explore.png
- images/icons/explore_on.png
- images/icons/mine.png
- images/icons/mine_on.png
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.io/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.io/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.io/custom-fonts/#from-packages
Error detected in pubspec.yaml
occured within compilation.
Logs
- Within compilation
Initializing hot reload...
#/properties/flutter: type: wanted [object] got null
Error detected in pubspec.yaml:
#/properties/flutter: type: wanted [object] got null
Error detected in pubspec.yaml:
- Ran flutter analyze and result didn’t mention it
nalyzing /Users/zhangyongchao/AndroidStudioProjects/alfraid...
lint • Name non-constant identifiers using lowerCamelCase at lib/Constants/Api.dart:2:23 • non_constant_identifier_names
lint • Name non-constant identifiers using lowerCamelCase at lib/Constants/Api.dart:5:23 • non_constant_identifier_names
lint • Prefer using /// for doc comments at lib/Utils/Network.dart:4:1 • slash_for_doc_comments
hint • Unused import: 'dart:convert' at lib/main.dart:1:8 • unused_import
hint • Unused import: 'package:flutter_swiper/flutter_swiper.dart' at lib/pages/Recommend.dart:2:8 • unused_import
hint • Unused import: 'dart:async' at lib/pages/Today.dart:1:8 • unused_import
hint • Unused import: 'dart:convert' at lib/Utils/Network.dart:2:8 • unused_import
hint • This class inherits from a class marked as @immutable, and therefore should be immutable (all instance fields must be final) at lib/Widgets/Avatar.dart:3:7 • must_be_immutable
8 issues found.
(Ran in 5.6s)
- Either after running
flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Mac OS X 10.13.5 17F77, locale zh-Hans-CN)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[!] iOS toolchain - develop for iOS devices (Xcode 9.3.1)
✗ ios-deploy not installed. To install:
brew install ios-deploy
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.25.1)
[✓] Connected devices (1 available)
Это мой код pubsepc.yaml
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
rxdart: ^0.27.1
path_provider: ^2.0.2
image_picker: ^0.8.0+3
pendatic: ^1.8.0
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
To add assets to your application, add an assets section, like this:
assets:
- assets/images/apple-in-hand.jpg
- assets/images/apricots.jpg
- assets/images/asparagus.jpg
Я постоянно получаю сообщение об ошибке, как показано ниже
PS C:UsersGeon-Young.Honge_commerce> flutter packages get
Error detected in pubspec.yaml:
Unexpected child "To add assets to your application, add an assets section, like this" found under "flutter".
Please correct the pubspec.yaml file at C:UsersGeon-Young.Honge_commercepubspec.yaml
При запуске Flutter Doctor проблем не обнаружено
PS C:UsersGeon-Young.Honge_commerce> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.0.4, on Microsoft Windows [Version 10.0.19042.1052], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] VS Code (version 1.57.0)
[√] Connected device (2 available)
Это информация о версии flutter & dart
Flutter 2.0.4 • channel stable • https://github.com/flutter/flutter.git
Framework • revision b1395592de (2 months ago) • 2021-04-01 14:25:01 -0700
Engine • revision 2dce47073a
Tools • Dart 2.12.2
Я не могу импортировать пакет rxdart, image_picker. (За пределами библиотеки есть каталог ресурсов), это может быть проблема, связанная с версией, или что-то еще.
Есть ли кто-нибудь, кто может мне помочь в этом вопросе?
Огромное спасибо!
3 ответа
Лучший ответ
Удалите раздел To add assets to your application, add an assets section, like this:
из pubspec.yaml
1
sajith lakmal
13 Июн 2021 в 05:59
Ошибка сообщает вам, что есть неожиданный дочерний элемент, "To add assets to your application, add an assets section, like this:"
этой строки там не должно быть, закомментируйте ее или удалите, ang pub get
должен работать нормально
1
Jaime Ortiz
13 Июн 2021 в 06:00
Замените этот код своим pubsepc.yaml всем приведенным ниже кодом.
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
rxdart: ^0.27.1
path_provider: ^2.0.2
image_picker: ^0.8.0+3
pendatic: ^1.8.0
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/images/apple-in-hand.jpg
- assets/images/apricots.jpg
- assets/images/asparagus.jpg
1
Atiqur Rahman
13 Июн 2021 в 09:37
Add Answer
|
View In TPC Matrix
Technical Problem Cluster First Answered On
August 9, 2022
Popularity
4/10
Helpfulness
1/10
Contributions From The Grepper Developer Community
Contents
Code Examples
Related Problems
TPC Matrix View Full Screen
Error detected in pubspec.yaml: Error on line 61, column 4: Expected a key while parsing a block mapping
Comment
0
Popularity
4/10 Helpfulness
1/10
Language
whatever
Source: stackoverflow.com
Tags: block
key
line
mapping
parsing
whatever
Contributed on Aug 09 2022
Tasia Jackson
6 Answers Avg Quality 4/10
I don’t know what is happening but I m not able to insert image through Asset image using pubspec.yaml
file.Pub get is not loading dependencies.
Kindly please help me out. I am running a flutter project.
Here is the code of pubspec.yaml
file
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
Error is :
Error detected in pubspec.yaml:
Expected «assets» to be a list, but got images/ (String).
Please correct the pubspec.yaml file at C:UserskhushAndroidStudioProjectsmi_card_flutterpubspec.yaml
Process finished with exit code 1
Действия по воспроизведению
Я получаю ошибку —
No file or variants found for asset: images/new.jpeg.
В то время как он находится в каталоге — fade_inassetsimagesnew.jpeg
Error building assets
FAILURE: Build failed with an exception.
* Where:
Script 'C:Userssacchflutterpackagesflutter_toolsgradleflutter.gradle' line: 435
* What went wrong:
Execution failed for task ':app:flutterBuildDebug'.
> Process 'command 'C:Userssacchflutterbinflutter.bat'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
BUILD FAILED in 9s
Finished with error: Gradle build failed: 1
I/flutter (17633): ══╡ EXCEPTION CAUGHT BY SERVICES ╞══════════════════════════════════════════════════════════════════
I/flutter (17633): The following assertion was thrown resolving an image codec:
I/flutter (17633): Unable to load asset: assets/images/new.jpg
I/flutter (17633):
I/flutter (17633): When the exception was thrown, this was the stack:
I/flutter (17633): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
I/flutter (17633): <asynchronous suspension>
I/flutter (17633): #1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:383:44)
I/flutter (17633): <asynchronous suspension>
I/flutter (17633): #2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:368:14)
I/flutter (17633): #3 ImageProvider.resolve.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:265:86)
I/flutter (17633): #4 ImageCache.putIfAbsent (package:flutter/src/painting/image_cache.dart:82:22)
I/flutter (17633): #5 ImageProvider.resolve.<anonymous closure> (package:flutter/src/painting/image_provider.dart:265:63)
I/flutter (17633): (elided 8 frames from package dart:async)
I/flutter (17633):
I/flutter (17633): Image provider: AssetImage(bundle: null, name: "assets/images/new.jpg")
I/flutter (17633): Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#27ad0(), name: "assets/images/new.jpg",
I/flutter (17633): scale: 1.0)
I/flutter (17633): ════════════════════════════════════════════════════════════════════════════════════════════════════
Журналы флаттера
Launching lib/main.dart on Pixel 2 in debug mode...
Initializing gradle... 1.4s
Resolving dependencies... 3.4s
Running 'gradlew assembleDebug'...
Error detected in pubspec.yaml:
No file or variants found for asset: images/new.jpeg.
Error building assets
FAILURE: Build failed with an exception.
* Where:
Script 'C:Userssacchflutterpackagesflutter_toolsgradleflutter.gradle' line: 435
* What went wrong:
Execution failed for task ':app:flutterBuildDebug'.
> Process 'command 'C:Userssacchflutterbinflutter.bat'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
BUILD FAILED in 10s
Gradle build failed: 1
Флаттер Доктор
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel beta, v0.5.1, on Microsoft Windows [Version 10.0.16299.431], locale en-IN)
[√] Android toolchain - develop for Android devices (Android SDK 28.0.0)
[√] Android Studio (version 3.1)
[√] Android Studio (version 3.0)
[√] IntelliJ IDEA Community Edition (version 2017.3)
[√] IntelliJ IDEA Ultimate Edition (version 2018.1)
[√] Connected devices (1 available)
• No issues found!
Ссылка на гитхаб —
https://github.com/Sacchid/fade_in
Все 18 Комментарий
Если изображения находятся в assets
(там, где они должны быть), путь в pubspec.yaml
должен включать это.
assets:
- assets/images/new.jpeg
- assets/umbrella.jpg
Смотрите также https://flutter.io/assets-and-images/
pubspec.yaml
Добавление pubspec.yaml
и main.dart
Или проверьте github https://github.com/Sacchid/fade_in/blob/master/pubspec.yaml#L27 .
name: fade_in
description: Fade in Flutter
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.0
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
assets:
- images/new.jpeg
- umbrella.jpg
основной дротик
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
<strong i="15">@override</strong>
Widget build(BuildContext context) {
final title = 'Fade in images';
//assets/images/umbrella.jpg
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: DecoratedBox(decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/new.jpg'
),
),
),
),
),
);
}
}
Вы рассматривали возможность попробовать мое предложение выше?
Ваши пути в pubspec.yaml
по-прежнему отсутствуют assets/....
Пожалуйста, проверьте мой комментарий выше еще раз. Он содержит assets
3 раза, ваш комментарий содержит его 1 раз.
Извините 😞, с моей стороны было очень глупо игнорировать/пропускать это.
И спасибо за то, что вы очень терпеливы. 😃
@zoechi Вы так мне помогли, документация Flutter находится на низком уровне.
flutter:
uses-material-design: true
assets:
- images/batwings.png
- images/batman.gif
fonts:
- family: Pacifico
fonts:
- asset: fonts/Pacifico-Regular.ttf
Это дает ту же проблему
Ресурс images/batwings.png не найден
для обоих.
Вот мой YAML
Home.dart
class BatmanImageWidget extends StatelessWidget{
<strong i="14">@override</strong>
Widget build(BuildContext context) {
// TODO: implement build
AssetImage batmanAsset=AssetImage('images/batwings.png');
Image image= Image(image: batmanAsset, width: 400.0, height: 400.0);
return Container(child: image);
}
Я все еще сталкиваюсь с проблемой. Я интегрировал вышеупомянутый файл main.dart и yaml в свой vscode, но не мир.
@ iam0thing какой именно каталог содержит batwings.png
и batman.gif
относительно каталога вашего проекта (каталога, содержащего pubspec.yaml
)?
Спасибо за ответ.
«относительно pubspec.yaml» — это ключевое слово, которое ускользало от моего понимания.
Я исправил путь
«lib/images/batwings.png»
и это сработало отлично.
1) Я добавил папку с ресурсами с помощью моей IDE — ВАЖНО!
2) Скопировал мой файл jpg в папку с ресурсами.
3) Добавлен путь в pubspec.yml
flutter:
assets:
- assets/my_image.jpg
4) Затем используйте изображение в файле дротика: ‘assets/my_image.jpg’
да. Я применил указанный подход. Это сработало. Спасибо за ответ
Попробуйте создать папку с ресурсами в корневом каталоге.
~/Desktop/flutter_app/assets
Вот мой YAML
flutter:
uses-material-design: true
assets:
- assets/[email protected]
в pubspec.yml добавить — assets/images/ при условии, что ваши изображения находятся в разделе assets/images
Затем используйте его на своих страницах. например AssetImage(«assets/images/img_i.jpg»)). Обратите внимание на косую черту
ресурсы:
- изображения / output-onlinepngtools.png
Эта строка выдает ошибки. Ресурс images/output-onlinepngtools.png не существует.
Попробуйте создать файл или исправить путь к файлу.dart(asset_does_not_exist)
// толстую стрелку => можно заменить на {}, что делает код более переформатированным
// главная функция — это отправная точка для всех наших флаттер-приложений
// Scaffold создает пространство для добавления всех виджетов
// теперь мы добавляем сверху панель приложений, она может иметь заголовок, иконку и т.д.
// Это main.dart
import ‘ package:flutter/material.dart ‘;
пустая функция() {
запустить приложение(
Материал Приложение(
дом: Эшафот(
backgroundColor: Colors.blueGrey,
панель приложения: панель приложения (
title: Text(‘Я богат’), backgroundColor: Colors.blueGrey[900]),
тело: Центр(
ребенок: Изображение(
изображение: AssetImage(‘images/output-onlinepngtools.png’),
),
),
),
),
);
}
Была ли эта страница полезной?
0 / 5 — 0 рейтинги
Issue Title | Created Date | Comment Count | Updated Date |
---|---|---|---|
JsonbAdapter Javadocs should clarify handling of null | 0 | 2021-06-15 | 2022-12-21 |
bug(messaging): lastRemoteMessage not stored on iOS | 4 | 2022-07-26 | 2023-02-07 |
Standardize contribution terms. | 1 | 2022-09-25 | 2023-01-13 |
VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00293(ERROR / SPEC) with Vulkan AMD 6900XT | 11 | 2022-09-14 | 2022-10-18 |
Distribute Robusta CLI via Scoop package manager for Windows | 1 | 2022-04-25 | 2022-09-06 |
Worker exited due to exception: com.intellij.openapi.progress.ProcessCanceledException | 3 | 2017-11-02 | 2022-12-23 |
RuntimeExceptionError when app is in background | 2 | 2020-12-31 | 2023-02-09 |
[Proposal] задержка использования запоминаемым рунам | 7 | 2022-08-04 | 2023-02-08 |
boosei.club | 1 | 2021-11-04 | 2022-01-02 |
lucikun.cc | 1 | 2021-11-04 | 2022-01-02 |
Ganool (54.39.39.152) | 1 | 2021-11-05 | 2022-12-11 |
Add examples in all supported formats | 1 | 2022-01-26 | 2023-02-08 |
Improve the README | 0 | 2021-08-06 | 2021-12-12 |
[Improvement] Clear preselection in 3D view if mouse cursor moves out of the 3D view | 0 | 2022-01-14 | 2022-10-18 |
[OCP-4.X][GCP] wrong install binary is being used for install | 0 | 2020-04-30 | 2023-01-10 |
开了tun system或者 proxy 天翼云登录不上 | 2 | 2022-10-29 | 2023-02-08 |
java.lang.IllegalStateException: org.slf4j.LoggerFactory in failed state | 0 | 2021-08-22 | 2023-01-30 |
Table increases by a few pixels after sizing divider | 0 | 2022-11-17 | 2023-01-30 |
Pseudoclasses not applied to node of controls when values are invalid from the start | 0 | 2022-08-25 | 2023-01-30 |
Video parsing result url is empty | 2 | 2022-07-15 | 2023-01-21 |
runtime error: invalid memory address or nil pointer dereference when running GetStream | 8 | 2022-05-26 | 2023-01-21 |
A few questions, from a fellow user of OpenEmu | 1 | 2021-10-30 | 2023-01-10 |
[GitInfoContributor] commit time is not human readable | 2 | 2021-06-28 | 2022-12-17 |
import-prefix-missing and not recognizing types from typescript | 0 | 2022-06-07 | 2023-01-24 |
How to support JWT authentication? | 4 | 2021-10-31 | 2023-02-04 |
Luxon 2.+ Breaks | 1 | 2021-08-06 | 2021-11-29 |
Request: setting for backup location | 9 | 2022-07-06 | 2023-01-31 |
rnaseq with slurm executor fails with tasks timing out | 2 | 2022-06-21 | 2023-01-19 |
Error en make test | 2 | 2021-01-22 | 2022-01-02 |
chess|move|a6a5|28562 | 1 | 2023-02-06 | 2023-02-02 |
not working on windows | 9 | 2020-05-28 | 2023-02-05 |
Button icons fail to appear correctly with the Monterey theme in firefox. | 8 | 2021-06-25 | 2023-02-08 |
Toogle Button not usable in Fast template | 0 | 2022-04-21 | 2023-01-25 |
2595 — PickByType | 0 | 2021-11-17 | 2022-01-13 |
Facing issue in implementing toggleable checkbox in datagridPro | 4 | 2022-01-14 | 2023-02-06 |
[BUG][JAVA/TYPESCRIPT] Invalid consumes headers generated | 4 | 2021-10-14 | 2022-12-20 |
Machine failures not propagated up to MachineDeployment.Status | 9 | 2021-11-10 | 2023-02-05 |
Swift Compiler Error Group | 1 | 2022-05-30 | 2023-02-05 |
Brazilian Portuguese Translation | 0 | 2021-08-12 | 2023-02-04 |
[Bug]: Issue with FirebaseApp not initialized on Android | 1 | 2022-10-23 | 2023-02-02 |
New release? | 3 | 2020-07-31 | 2021-12-19 |
Intellisense loading endlessly | 3 | 2022-08-03 | 2022-09-18 |
Mac M1 pip installation error | 1 | 2023-01-12 | 2023-02-07 |
Disk read and write too fast, resulting in server lag, how to reduce read and write speed | 0 | 2022-10-18 | 2023-01-23 |
The final accuracy rate during evaluation is too low | 3 | 2020-10-09 | 2023-02-08 |
grep does not filter with 2 brackets together | 2 | 2022-04-22 | 2023-01-02 |
Action Required: Fix Renovate Configuration | 0 | 2020-07-05 | 2022-11-29 |
antd scrollbar disappered after filter | 2 | 2021-09-10 | 2022-11-26 |
Document the PR Wrangler Shadow Program for SIG Docs | 2 | 2022-02-27 | 2023-02-04 |
Content Update — Rework on Backend API Page | 1 | 2022-09-29 | 2023-02-08 |
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.