Skip to main content

Flutter Load Local Image From Assets

Local images are very useful in mobile apps. They can be loaded anytime in app without even network access. If you are creating a app which shows few data on app start time to improve user experience then local images are a very good options for visual representation. To add local images in flutter we have to make few changes in our flutter app directory. Image.asset() widget is used to display local image in flutter.

Flutter Load Local Image From Assets:

1. Open your flutter project root directory and Create a folder named as assets.
Create Assets folder in flutter app
2. Creating images folder inside assets folder.
Images Folder in flutter app
3. Copy your image in the images folder.
Copy Image in folder in flutter app
4. Add assets images folder path in pubspec.yaml file.
flutter:
  uses-material-design: true

  assets:
    - assets/images/
    - google_fonts/
Source code of pubspec.yaml file:
name: myapp
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1

environment:
  sdk: ' > =3.0.5 < 4.0.0 '
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  cupertino_icons: ^1.0.2
  url_launcher: ^6.1.12
  flutter_widget_from_html_core: ^0.10.3
  google_fonts: ^5.1.0
  flutter_screenutil: ^5.8.4
  easy_rich_text: ^2.0.0

dev_dependencies:
  intl: ^0.18.0-nullsafety.2
  flutter_test:
    sdk: flutter

  flutter_lints: ^2.0.0

flutter:
  uses-material-design: true

  assets:
    - assets/images/
    - google_fonts/
5. Creating a String variable and pass Image path as String inside it.
final String flowerImage = 'assets/images/flower.jpg';
6. Creating Image.asset() widget and passing image path string inside it.
Image.asset(flowerImage, fit: BoxFit.fitWidth)
Source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({super.key});

  final String flowerImage = 'assets/images/flower.jpg';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: SafeArea(
                child: Center(
      child: Image.asset(flowerImage, fit: BoxFit.fitWidth),
    ))));
  }
}
Screenshot:
Flutter Load Local Image From Assets

Comments