In this tutorial you will learn how to load a list of images from an external URL into Flutter. The external URL we use provides a list of images in JSON format. We will create a mobile Flutter application that will display this list of images in the GridView.

In order to achieve our main goal, we will follow the next steps:

  1. Create a new Flutter application,
  2. Download Addictions,
  3. Create a function to retrieve JSON from the external API,
  4. Function call in initState,
  5. Display images in GridView.

1. Creating a new Flutter application

First we need to create a new Flutter project in Android Studio (or any other IDE you use). If you don’t know how to create a project, you can consult the Hello World App in Flutter tutorial.

2. Download dependencies

In this lesson we will use a dependency called HTTP. The HTTP Dependency is a composite, cross-platform, forward-looking API for HTTP requests. This package contains a number of functions and classes that facilitate the use of HTTP resources.

Open your pubspec.yaml folder:

and add http: ^0.12.2 under dependencies :

Loading Images from a Remote URL in Flutter

Please note that the latest version at the time of writing this manual is 0.12.2. You should check which is the latest version when you use it. Then open a terminal window, go to the current directory where your Flutter project is located and execute the command pub to get the dependencies in the pubspec.yaml file. You can then import the HTTP package into your code as shown in the figure below.

Loading Images from a Remote URL in Flutter

3. Create a function for receiving JSON.

To retrieve JSON with a list of images from an external URL via an HTTP package, we need the following function.

List of data;
List ofUrl images = [] ;

Future async fetchDataFromApi() {
var jsonData = waitit http.get(
https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/tutorials/files/cats.json) ;
var fetchData = jsonDecode(jsonData.body) ;

setState(() {data = fetchData;data.forEach((element) {imagesUrl.add(element[‘url’]));})

Success again;
}““

Let’s dissect the above function to better understand it. First we declare a jsonData variable, which is set on the JSON object we receive via the HTTP package.

Once the JSON data has been obtained, we need to decode them using the standard dart:convert package. After decoding the JSON data, we can use it to store the result in a list. As you can see, we’ve announced two lists. The first list, called data, saves the JSON objects after decoding. In the second list, called imagesUrl, we add all the URLs of images read from JSON objects. We will use these URLs to display the images. Next, we use the forEach() function to browse the collection of JSON objects stored in the data list, and for each item we read its URL property and add its value to the imagesUrl list. Eventually we’ll just go back to Success to finish the job.

4. Call to retrieve data from IPi()

In the previous step we prepared the function fetchDataFromApi(). Now that this function is finished, we can call it in the initState() function. This means that fetchDataFromApi() is called when the widget is initialized and inserted into the tree. See example code below:

@override
void initState() {
super.initState();
fetchDataFromApi();
}

5. Displaying images in grid view

Now that we have retrieved a list of image URLs from the external JSON, we are ready to display these images in our mobile Flutter application. As mentioned above, it is best to display the images in a frame or grid view. In the following example code we use GridView.builder.

GridView.builder(
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemCount: imagesUrl.length,
itemBuilder : (BuildContext, int index) {
return Image.network (
imagesUrl [index],
fit: BoxFit.cover,
);
},
),

In GridView.builder we pass the required gridDelegate property and then give it the property SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), which basically means that we want to display our images on 2 columns. Next, the itemCount property defines the length of the imageUrl list. Finally, in theBuilder item, we give a network image whose URL path is set to imagesUrl [index]. This means that we get one image per URL stored in the imagesUrl list.

Here’s the output of our code:

Loading Images from a Remote URL in Flutter

Example of complete code

Below is an example of complete code that can be copied and executed in the IDE.

input ‘dart:convert’ ; input
‘package:flutter/material.dart’ ; input
‘package:http/http.dart’ into http ;

void main() => runApp(MyApp()) ;

The MyApp class extends the StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner : false,
home : HomePage(),
);
}
}.

The HomePage class extends the StatefulWidget {
@override
_HomePageState createState() => _HomePageState() ;
}.

The HomePageState class extends the State [
List Data;
List Data imagesUrl = [];

@override
void initState() {
super.initState();
fetchDataFromApi();
}

Future async fetchDataFromApi() {
var jsonData = waitit http.get(
https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/tutorials/files/cats.json) ;
var fetchData = jsonDecode(jsonData.body) ;

setState(() {data = fetchData;data.forEach((element) {imagesUrl.add(element[‘url’]);})

success of return;
}

@override
Widget build(BuildContext context) {
returns Scaffold(
appBar : AppBar(
automaticImplyLeading : false, title
: Text(‘List Of Images’),
centerTitle : true,
),
body :
GridView.builder (
gridDelegate :
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount : 2),
itemCount : imagesUrl.length,
itemBuilder : (BuildContext context, int index) {
return Image.network (
imagesUrl [index],
fit: BoxFit.cover,
);
},
),
);
}
}.

I hope you found this lesson about Flutter useful. If you want to know more about Flutter, see the other Flutter tutorials on this page. Some of them contain video tutorials.

flutter display image from url,flutter network image not showing,flutter network image placeholder,flutter network image error handling,flutter image gallery,flutter image,flutter download image from url,flutter lazy loading images,image.network flutter size,flutter cached network image,flutter display image from file

You May Also Like

Steps To Start And Join Live Voice Chat On Telegram

To attract more users to its cloud-based instant messaging solution, Telegram announced…

4 Browsers that are Super Awesome

Facebook Twitter Pinterest Reddit Messenger WhatsApp Xbox One supports a wide range…

Discord installation has failed in Windows 10

Talk about the most popular Voice over IP (VoIP) application used by…

URBN Power Bank Review, Made In India Power Bank, 18W, QC 3.0 + PD

The Indian smartphone accessory brand URBN has recently launched its latest thin…