flutter-tutorial

Flutter Images

Every program relies heavily on images. They might serve as visual aids for important information or simply improve the appearance of your software. You can add a picture to your Flutter application in a variety of ways. This article will provide a thorough overview of the various methods, as well as detailed examples and sample code.

Image.asset

This is the most easiest way to add a photo, albeit it does require some preparation. Create an assets folder first. Any external media, such as photographs, movies, gifs, or JSON files, should be placed in this folder. It is recommended that you create distinct subfolders for each type of asset in your app if it will contain various sorts of assets. The assets folder in your project should be in the same directory as the pubsec.yaml file.

The pubsec.yaml file must be modified to incorporate the image once it has been added to the assets folder. The pubsec.yaml file must also include any external resources or packages used in your software.

Here is code for a simple app that uses Image.asset to display an image:

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Image Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Image Demo'),
        ),
        body: new Container(
          color: Colors.grey[200],
          child: new Image.asset('assets/tree.jpg'),
          alignment: Alignment.center,
        ),
      ),
    );
  }
}

Image.network

You must use Image.network to display an image from the internet rather than one saved locally. Simply copy the picture address after checking the licence and copyright of the selected image. Whether you’re testing your app on an emulator or a hardware device, make sure it’s connected to the internet or it’ll fail.

Here is code for a simple app that uses Image.network to display an image

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Image Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Image Demo'),
        ),
        body: new Container(
          color: Colors.grey[200],
          child: new Image.network(
            'https://images.pexels.com/photos/1525043/pexels-photo-1525043.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
          ),
          alignment: Alignment.center,
        ),
      ),
    );
  }
}

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *