Adding Multiple images in flutter using function?

5,956

enter image description here

As you used assets images in your code, so I am also posting the code for assets, you can change logic accordingly. Here is the sample code.

int _count = 0;
List<String> _listImages = [
  "assets/images/chocolate_pic.png",
  "assets/images/profile.png",
  "assets/images/loading.gif",
];

@override
Widget build(BuildContext context) {
  return Scaffold(
    floatingActionButton: FloatingActionButton(onPressed: _addImages, child: Icon(Icons.add),),
    body: Padding(
      padding: const EdgeInsets.all(8.0),
      child: GridView.builder(
        itemCount: _listImages.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, mainAxisSpacing: 20, crossAxisSpacing: 20),
        itemBuilder: (_, index) {
          return Image.asset(_listImages[index], fit: BoxFit.cover, width: 100, height: 100);
        },
      ),
    ),
  );
}

void _addImages() {
  setState(() {
    _listImages.add(_listImages[_count % 3]);
    ++_count;
  });
}
Share:
5,956
Prianca
Author by

Prianca

Updated on December 12, 2022

Comments

  • Prianca
    Prianca over 1 year

    I am not encountering any problem but I have a question as I have to add multiple images in my app. Suppose in future these images can get large in numbers so I just wanted to know that how can we use a function in flutter.

    This is how I am adding images as for now:

    
            Container(color: Colors.redAccent, height: 2),
            SizedBox(height: 8),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(
                  child: Image.asset(
                    'assets/cat.jpg',
                    width: 110.0,
                    height: 100.0,
                    fit: BoxFit.fill,
                  ),
                ),
                Spacer(flex:1),
                Expanded(
                  child: Image.asset(
                    'assets/cat.jpg',
                    width: 110.0,
                    height: 100.0,
                    fit: BoxFit.cover,
                  ),
                ),
              ],
            ),
    

    Expected:

    enter image description here

    My output:

    enter image description here

  • Prianca
    Prianca almost 5 years
    I will let you know this when I will add this. As of now I have question on how to add a line on tapping one dot (I am thinking of adding a line as an image onTapping any of dot ) . So how can I achieve that?
  • CopsOnRoad
    CopsOnRoad almost 5 years
    If you can show me the screenshot of what you are trying to achieve I can help you better.