Search code examples
flutterassetsdisplay

image doesn't display on the app even though it was in assets folder


I added the image file on assets folder. but when I run the app, image doesn't display at all. and there isn't any error message. I don't know the reason why I cannot see the picture I added. (of course, it isn't the white picture. It isthe normal picture.) Please let me know the reason.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Title'),
      ),
      body: Center(
        child: GestureDetector(
          onTap: (){
            Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => HeroDetailPage()),
            );
          },
          child: Hero(
            tag: 'image',
            child: Image.asset(
                'assets/sample.jpg',
              width: 100,
              height: 100,
            ),
          ),
        ),
      ),
    );
  }
}

class HeroDetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hero Detail'),
      ),
      body: Hero(
        tag: 'image',
        child: Image.asset('assets/sample.jpg'),
      ),
    );
  }
}

sample.jpg is in the assets folder


Solution

  • Please check: https://flutter.dev/docs/development/ui/assets-and-images first.

    There you can find this:

    Flutter uses the pubspec.yaml file, located at the root of your project, to identify assets required by an app.

    Here is an example:

    flutter:
      assets:
        - assets/my_icon.png
        - assets/background.png
    

    To include all assets under a directory, specify the directory name with the / character at the end:

    flutter:
      assets:
        - directory/
        - directory/subdirectory/