user3523406
user3523406

Reputation: 575

Unable to Load Asset in Flutter Web

I am currently learning Flutter for Web and have encountered an error when trying to load an image asset. Despite following the typical asset loading procedures, I'm facing an "Unable to load asset" error. Here’s a detailed breakdown of my issue, including the relevant code snippets and file structure:

lib/main.dart

import 'package:dogs/profile_screen.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ProfileScreen(),
    );
  }
}

lib/profile_screen.dart

import 'package:flutter/material.dart';

class ProfileScreen extends StatelessWidget {
  const ProfileScreen({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: const [
          ProfileImage(),
          ProfileDetails(),
          ProfileActions(),
        ],
      ),
    );
  }
}

class ProfileImage extends StatelessWidget {
  const ProfileImage({super.key});
  @override
  Widget build(BuildContext context) {
    return ClipOval(
      child: Image.asset(
        width: 200,
        height: 200,
        'assets/dog1.jpg',
        fit: BoxFit.fitWidth,
      ),
    );
  }
}

class ProfileDetails extends StatelessWidget {
  const ProfileDetails({super.key});
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Wolfram Barkovich',
            style: TextStyle(fontSize: 35, fontWeight: FontWeight.w600),
          ),
          _buildDetailsRow('Age', '4'),
          _buildDetailsRow('Status', 'Good Boy'),
        ],
      ),
    );
  }

  Widget _buildDetailsRow(String heading, String value) {
    return Row(
      children: [
        Text(
          '$heading: ',
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        Text(value),
      ],
    );
  }
}

class ProfileActions extends StatelessWidget {
  const ProfileActions({super.key});
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        _buildIcon(Icons.restaurant, 'Feed'),
        _buildIcon(Icons.favorite, 'Pet'),
        _buildIcon(Icons.directions_walk, 'Walk'),
      ],
    );
  }

  Widget _buildIcon(IconData icon, String text) {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        children: <Widget>[
          Icon(icon, size: 40),
          Text(text),
        ],
      ),
    );
  }
}


pubspec.yaml

assets:
  - assets/
$ ls -1 assets/
dog1.jpg
khachik-simonian-nXOB-wh4Oyc-unsplash.jpg

Error Message

Launching lib/main.dart on Chrome in debug mode...
Waiting for connection from debug service on Chrome...
This app is linked to the debug service: ws://127.0.0.1:38105/pGd3EEhWs90=/ws
Debug service listening on ws://127.0.0.1:38105/pGd3EEhWs90=/ws
Debug service listening on ws://127.0.0.1:38105/pGd3EEhWs90=/ws
Error while trying to load an asset: Flutter Web engine failed to fetch "assets/assets/dog1.jpg". HTTP request succeeded, but the server responded with HTTP status 404.

======== Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: "assets/dog1.jpg".

The asset does not exist or has empty data.
When the exception was thrown, this was the stack: 
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 297:3  throw_
packages/flutter/src/services/asset_bundle.dart 324:9                        <fn>
dart-sdk/lib/async/zone.dart 1661:54                                         runUnary
dart-sdk/lib/async/future_impl.dart 162:18                                   handleValue
dart-sdk/lib/async/future_impl.dart 838:44                                   handleValueCallback
dart-sdk/lib/async/future_impl.dart 867:13                                   _propagateToListeners
dart-sdk/lib/async/future_impl.dart 643:5                                    [_completeWithValue]
dart-sdk/lib/async/future_impl.dart 713:7                                    callback
dart-sdk/lib/async/schedule_microtask.dart 40:11                             _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5                              _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:7           <fn>
Image provider: AssetImage(bundle: null, name: "assets/dog1.jpg")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#d5033(), name: "assets/dog1.jpg", scale: 1)
====================================================================================================

Upvotes: 0

Views: 1336

Answers (3)

Ngoun Lyborey
Ngoun Lyborey

Reputation: 68

  1. Make sure your folder "assets" and code in pubspec.yaml are the same
flutter:
  uses-material-design: true
  assets:
    - assets/
  1. You should write Image like this
Image.asset(
   'assets/dog1.jpg',
    width: 200,
    height: 200,
    fit: BoxFit.fitWidth,
)
  1. run flutter clean then flutter pub get and if possible restart you sdk

Upvotes: 2

Andreas Hadjimamas
Andreas Hadjimamas

Reputation: 453

Inside your pubspec.yaml file make sure you have the following

flutter:
  uses-material-design: true
  assets:
    - assets/

Then run flutter pub get command

Upvotes: 0

Aiman
Aiman

Reputation: 161

Ensure that your assets path is correctly indented.

flutter:
  assets:
    - assets/

Head to this answer.

Upvotes: 2

Related Questions