Gridview builder range error index flutter

GestureDetector( onTap: (){ getImages(); }, child: SizedBox( width: MediaQuery.of(context).size.width, height: 155, child: selectedImagesnew.isEmpty ? const Center(child: Text('Add Images') )

                           : GridView.builder(

                         scrollDirection: Axis.horizontal,
                         itemCount: 4,
                         gridDelegate:
                         const SliverGridDelegateWithFixedCrossAxisCount(
                             crossAxisCount: 1

                         ),
                         itemBuilder: (BuildContext context, int index) {
                           // TO show selected file
                           return Container(
                             decoration: BoxDecoration(
                               border: Border.all(
                                 color: Colors.black26
                                 ,width: 2
                               )
                             ),
                             child: kIsWeb
                                     ? Image.network(
                                     selectedImagesnew[index].path)
                                     : Image.file(selectedImagesnew[index]),
                           );

                         },
                       ),
                      ),
                    ),

After adding a first image, as you can see item count is 4 .I am getting Range error index only valid value is 0:1 in the remaining three containers. And when I tap the second container photo is getting uploaded but it still shows error in the remaining containers. enter image description here

Upvotes: 0

Views: 114

Answers (1)

Because your list selectedImagesnew not sure have 4 elements after you fetch data (maybe your getImages() function).

you need change:

itemCount: 4,

to:

itemCount: selectedImagesnew.length,

Upvotes: 2

Related Questions