Home > Net >  Not able to load image in flutter package
Not able to load image in flutter package

Time:03-17

I've created a flutter package and images are inside images folder.

flutter:
  uses-material-design: true
  # To add assets to your package, add an assets section, like this:
  # assets:
  assets:
    - images/
    - images/location_pointer.png

I'm trying to load this image:

Widget build(BuildContext context) {
    return Scaffold(
        body: Image.asset(
          'images/location_pointer.png',
          width: 22.0,
          height: 44.0,
          fit: BoxFit.fill,
        ));
}

I've created a project and importing a package inside it:

dependencies:
  flutter:
    sdk: flutter
  abc_pkg:
    path: /Users/mosh/Documents/flutter proj/abcPackage/abc_pkg

I'm able to load the package when run this project but not able to load the images inside the package.

======== Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: images/location_pointer.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:675:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "images/location_pointer.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#092c6(), name: "images/location_pointer.png", scale: 1.0)
====================================================================================================

CodePudding user response:

  1. Make sure all your images are saved inside a directory called 'images', which is inside a directory called 'assets'.

  2. Update your pubspec.yaml as follows:

flutter:
  uses-material-design: true
  # To add assets to your package, add an assets section, like this:
  # assets:
  assets:
    - assets/images/location_pointer.png
    

  1. Update your dart file as follows:

Widget build(BuildContext context) {
    return Scaffold(
        body: Image.asset(
          'assets/images/location_pointer.png',
          width: 22.0,
          height: 44.0,
          fit: BoxFit.fill,
        ));
}

CodePudding user response:

please try this code. and make an image folder in the same directory where you have the lib folder

in your pubspec.yaml file

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

and in your dart file

    Widget build(BuildContext context) {
    return Scaffold(
        body: Image.asset(
          'images/location_pointer.png',
          width: 22.0,
          height: 44.0,
          fit: BoxFit.fill,
        ));
}
  • Related