Open In App

Flutter – Dynamic Image List

Last Updated : 12 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Dynamic Image List is the list of Images when we add images Dynamically, In this article, we will see how to add images dynamically to the List of Images. It is something like that we are adding some items to the list. There is no need to add dependency to our project. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Create an Empty project. And add the material library into the main file.

Dart




import 'package:flutter/material.dart';


Step 2: Now call the main method, Into this run the runApp method that will run our app or class.

Dart




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


Step 3: Now we have to create a stateful widget A4Run.

Why stateful?

Because we are implementing dynamically so that the state of the app changes. Create a stateful class A4Run. And return the scaffold, add the AppBar.

Dart




class A4Run extends StatefulWidget {
  A4Run() : super();
  
  @override
  A4RunState createState() => A4RunState();
}
class A4RunState extends State<A4Run> {
    @override
  Widget build(BuildContext context) {
    // finding length of the list
    var ImgCount=imgList.length; 
  
    // scaffold with appbar 
    return Scaffold( 
      // appbar with leading icon and title
      appBar: AppBar(
        leading:Icon(Icons.image),
        title: Text("Dynamic Add Image List"),
      ),
      );
  }
}


In the project, we are using three images, And making the list of them imgList, so that we pick random picks from the list dynamically and then add images back to the list.

Dart




// list of images
List imgList = [  
    Image.asset('Images/S1.png'),
    Image.asset('Images/S3.png'),
    Image.asset('Images/S2.png'),
  ];


Don’t forget to add the image in the asset of the pubspec.yaml file. Otherwise, this will throw an error. You may refer to this article for the same. The thought process is that we will make a ListView and Add item count and a button to add the image. and append the image. 

Step 4: Now in the body of the scaffold, Create a ListView widget, In ListView first, we will use the row to show the item count and a button. Now add one more child to the listview, which will show the list of images.

Dart




body:
    Padding(
      padding: const EdgeInsets.all(12.0),
      // listview with scroll
      // direction vertical
      child: ListView ( 
        scrollDirection: Axis.vertical, 
        // listview children 
        children: [ 
          Row(
            children: [
              // image count in the list
              // or length of the list
              Text("Image Count:$ImgCount"), 
              SizedBox(width:45),
              // icon button to add 
              // the image to the list
              FlatButton.icon( 
                icon:Icon(Icons.add),
                label:Text("Add Image"),
                // when pressed call
                // the add method 
                onPressed:(){   
                   
                },
              )
            ]
             // traversal in the list
             // and display each image .
             for(var item in imgList)
            Center(
              child:Container(
                  width:200,
                  height:150,
                  child:item
              ),
            )
          ),
        ],
        ),
      ),


Step 5: Now make a method that will take the random images for the list and then again add it back to the list.

Dart




// AddRandomImage method to add
// the image to the list  
void AddRandomImage(){
    // random image select in range 0-3
    var RandImgIndex=new Random().nextInt(3); 
  
    // if index =0 pick image that is on 0 index 
    if(RandImgIndex==0){ 
      imgList.add(Image.asset('Images/S1.png'));
    }
    // if index =1 pick image at index 1
    else if(RandImgIndex==1){ 
      imgList.add(Image.asset('Images/S2.png'));
    }
    // pick image at 3 index
    else{  
      imgList.add(Image.asset('Images/S3.png'));
    }
  }


Step 6: And finally in onpressed property call the setState method and into it call the AddRandomImage Method.

Dart




onPressed:(){
   // setstate method to call the
   // method AddRandomImage 
   setState(() {  
        AddRandomImage();
      });
},


Complete Code

Dart




import 'dart:math';
import 'package:flutter/material.dart';
  
// main method with runapp runs the class A4Run
void main() => runApp(A4Run());
  
class A4Run extends StatefulWidget {
  A4Run({Key? key}) : super(key: key);
  
  @override
  A4RunState createState() => A4RunState();
}
  
class A4RunState extends State<A4Run> {
  // list of images 
  List imgList = [
    Image.asset('Images/S1.png'),
    Image.asset('Images/S3.png'),
    Image.asset('Images/S2.png'),
    Image.asset('Images/S2.png'),
  ];
      
  // method to add images dynamically
  void AddRandomImage() {
    var RandImgIndex = Random().nextInt(3);
      
    // if index is 0 we will pick image at index 0
    if (RandImgIndex == 0) {
      imgList.add(Image.asset('Images/S1.png'));
      // if index is 1 we will pick image at index 1
    } else if (RandImgIndex == 1) {  
      imgList.add(Image.asset('Images/S2.png'));
    } else {  
      // if index is 2 we will pick image at index 2
      imgList.add(Image.asset('Images/S3.png'));
    }
  }
  
  @override
  Widget build(BuildContext context) {
    // count of the list of image
    var ImgCount = imgList.length; 
  
    // MaterialApp with debugShowCheckedModeBanner false
    return MaterialApp(  
      debugShowCheckedModeBanner: false,
      home: Scaffold( 
        appBar: AppBar(
          leading: Icon(Icons.image),
          title: Text("Dynamic Add Image List"),
        ),
        body: Padding(
          padding: EdgeInsets.all(12.0),
          // list view to show images and list count
          child: ListView(  
            scrollDirection: Axis.vertical,
            children: [
              Row(children: [
                // showing item count
                Text("Image Count:$ImgCount"), 
                SizedBox(width: 45),
                // icon button to call the
                // method AddRandomImage 
                OutlinedButton.icon( 
                  icon: Icon(Icons.add),
                  label: Text("Add Image"),
                  onPressed: () {
                    setState(() {
                      // calling method
                      AddRandomImage(); 
                    });
                  },
                )
              ]),
              // showing list of images
              for (var item in imgList)
                Center(
                  child: Container(width: 500, height: 350, child: item),
                )
            ],
          ),
        ),
      ),
    );
  }
}


Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads