Leandro
Leandro

Reputation: 1522

Error when loading an image from the assets

I am trying to use a PNG file as an icon image.

I have an assets folder in the root of my project.

The file's path is assets/icons/Dumbbell.png.

I loaded my assets in the pubspec file:

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

And in a Stateful widget's state I'm trying to use it:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      ...
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
           BottomNavigationBarItem(
            title: Text('Workout'),
            icon: Image.asset(
              'assets/icons/Dumbbell.png',
            ),
          ),
        ],
      ),
    );
  }

I just can't make it work!

EDIT: I removed the const keyword and added another BottomNavigationBarItem and now everything is working perfectly!

Upvotes: 3

Views: 1796

Answers (3)

null
null

Reputation: 573

try again with this demo

Image(image: AssetImage('assets/images/intro_0.jpg'),fit: BoxFit.fitWidth,)

diegoveloper's words is right. and BottomNavigationBar need two more items. those code worked:

    bottomNavigationBar:BottomNavigationBar(
        items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
                title: Text('Workout'),
                icon: Image(image: AssetImage('assets/images/intro_0.jpg'),fit: BoxFit.fitWidth,),
            ),
            BottomNavigationBarItem(
                title: Text('Workout'),
                icon: Image(image: AssetImage('assets/images/intro_0.jpg'),fit: BoxFit.fitWidth,),
            ),
        ],
    ),

Upvotes: -1

diegoveloper
diegoveloper

Reputation: 103421

To fix your issue, just remove the const keyword because your icon is not constant and also you need at least two BottomNavigationBarItem widgets to make it work:

    items: [
           BottomNavigationBarItem(
            title: Text('Workout'),
            icon: Image.asset(
              'assets/icons/Dumbbell.png',
            ),
          ),
          BottomNavigationBarItem(
            title: Text('Another item'),
            icon: Image.asset(
              'assets/icons/Dumbbell.png',
            ),
          ),
        ],

More info here: https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html

Upvotes: 4

Nikunj B Patel
Nikunj B Patel

Reputation: 189

try this..

use ImageIcon class instead of Image.asset

 bottomNavigationBar: BottomNavigationBar(
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
                icon: ImageIcon(AssetImage("assets/mascot.png")),
              title: Text("workout"),
            ),

          ],
 ), 

Upvotes: -1

Related Questions