#android #flutter #android-studio #dart
Вопрос:
Я пытаюсь создать приложение, в котором при нажатии плоской кнопки изображение должно измениться
Это мой Код .Здесь изображение не может загружаться .Это создает некоторое исключение, несмотря на мое
файл pubspec.yaml верен.Может кто-нибудь мне помочь?Я пытаюсь использовать случайную функцию внутри моей плоской кнопки для обновления изображений при нажатии.
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(Magic());
}
class Magic extends StatefulWidget {
const Magic({Key? key}) : super(key: key);
@override
_MagicState createState() => _MagicState();
}
class _MagicState extends State<Magic> {
var i=1;
@override
Widget build(BuildContext context) {
return MaterialApp(
home:Scaffold(
backgroundColor:Colors.blue,
appBar: AppBar(
centerTitle: true,
title:Text( 'Ask Me Anything',
style: TextStyle(
color: Colors.white,
),
),
backgroundColor: Colors.blue[900],
),
body: Container(
child:FlatButton(
onPressed: () {
setState(() {
i = Random().nextInt(5) 1;
});
},
child:Image(
image:AssetImage('images/dice$i.png'),
)
),
),
)
);
}
}
Мой файл Pubspec.yaml
name: magicball
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# 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.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0 1
environment:
sdk: ">=2.12.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: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/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/ball1.png
- images/ball2.png
- images/ball3.png
- images/ball4.png
- images/ball5.png
- images/dice1.png
- images/dice2.png
- images/dice3.png
- images/dice4.png
- images/dice5.png
- images/dice6.png
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/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.dev/custom-fonts/#from-packages
В этом и заключается ошибка
The following assertion was thrown resolving an image codec:
Unable to load asset: images/dice4.png
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: "images/dice4.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#70fe4(), name: "images/dice4.png", scale: 1.0)
====================================================================================================
Комментарии:
1. пожалуйста, поделитесь своей структурой проекта для каталога изображений.
2. Готово !!..Пожалуйста, проверьте это сейчас!
3. Кажется, все в порядке. Попробуйте flutter clean, затем нажмите «Получить» и снова запустите приложение
Ответ №1:
создайте assets
папку и поместите images
ее туда. и измените путь на - assets/images/ball1.png
. или вы можете просто поместить ссылку на папку там.