skip to Main Content

How to make List.generate with condition? I got error paused on exception

I cant display image from firebase array

there is my code

Obx(
  () => Row(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: List.generate(
      3,
      (index) => data['p_imgs'][index] != ''
        ? Image.network(
          data['p_imgs'][index],
          width: 100,
        ).onTap(() {
          controller.pickImage(index, context);
        })
        : productImages(label: "+").onTap(() {
          controller.pickImage(index, context);
        }),
    ),
  ),
),

2

Answers


  1. Normally you need to provide the length of the List if you want to use List.generate and if you use conditions you will not be able to know the exact length. If you want to filter you would need to know the length beforehand.

    Instead of this, you can use List.where, like this

      List<int> numbers = List.generate(100, (index) => index + 1).where((number) => number % 2 == 0).toList();
    

    Now first this will generate a list of 100 numbers and then filter out the numbers using the given condition, here it is if the number is divisible by 2 or not.

    Hope it helps!!!

    Login or Signup to reply.
  2. to generate a list of images, i think that is what you want to achieve, you can do following

    data['p_imgs']
    .map((path) {
        if (path != ''){
            return Image.network(path, width: 100,)..onTap(() { controller.pickImage(index, context); });
        }
        else {
            return productImages(label: "+")..onTap(() {
              controller.pickImage(index, context);
            });
        }
    } 
    

    what does this,
    the map function iterates over the array and you can give a other type back. So in this code we iterate over the string array and give for every string a networkimage back

    map function docu

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search