In Flutter application we can insert images, using local images or using images online by inserting the image url into the code.
Online ImagesIn this example we’re inserting image into the Body widget. We first remove the text, then we use the code as below.
body: Center( //LOCATED IN THE MIDDLE child: Image( image: NetworkImage('https://www.xantheberkeley.com/wp-content/uploads/2013/10/sky_xantheberkeley.jpg')//image url ), )
The result is as follow :
-Assets Images
If we wish to use local images, we use AssetImage() to do, instead of Internet url, we insert a local url.
we first create a new directory, let’s call it assets
.
Then, we drag some downloaded images into the directory. Before we insert local images, we need to make some changes in the pubspec.yaml file, so that we can use these images as our assets.
Very similar to the one we do on the font, we modify the assets part in the pubspec.yamlfile.
Then inside the assets directory.
From now on we can use any images inside the assets directory.
import 'package:flutter/material.dart';void main() => runApp(MaterialApp( home: home(),));class home extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( //ROOT WIDGET appBar: AppBar( title: Text( 'CodeForces', style: TextStyle( fontSize: 25.0, letterSpacing: 2.0, color: Colors.white, fontFamily: 'BebasNeue', ), ), //SET THE TITLE TEXT centerTitle: true, //SET THE PROPERTIES, WHERE THE TEXT SHOWED AT THE CENTRE backgroundColor: Colors.red, ), body: Center( //LOCATED IN THE MIDDLE child: Image( image: AssetImage('assets/1.jpg') ), ), floatingActionButton: FloatingActionButton( //CREATE A FLOATING BUTTON child: Text('click'), backgroundColor: Colors.red[600], ), ); }}
There’s also a short version for more easier coding.
For Network Images:body: Center( //LOCATED IN THE MIDDLE child: Image.network('url'), ),
For Assetsbody: Center( //LOCATED IN THE MIDDLE child: Image.asset('url'), ),
Flutter Tutorial for Beginners #8 - Images & Assets