как добавить изображения в Listview.builder в сети флаттера

Я новичок в флаттере. Я хочу добавить несколько изображений, а также одно на флаттер-сайт, который я создаю. Я не могу этого сделать, я просмотрел много уроков, но ничего не помогло мне. вот почему я пришел сюда. Это то, что я сделал до сих пор...

      final picker = ImagePicker();
List<File> images = [];
List<int> imageFiles = [];
void _imgFromGallery() async {
List<XFile>? files = await picker.pickMultiImage(
  imageQuality: 50,
);
if (files != null) {
  for (var element in files) {
    setState(() {
      images.add(File(element.path));
    });
  }
}

}

Здесь я добавляю изображения в ListView.Builder

      Text(
                          'Attachments',
                          style: AppTextStyles.boldBlack,
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        images.isEmpty
                            ? const SizedBox()
                            : SizedBox(
                          height: 90,
                          child: ListView.builder(
                            shrinkWrap: true,
                            itemCount: images.length,
                            scrollDirection: Axis.horizontal,
                            itemBuilder: (context, index) {
                              return Row(
                                crossAxisAlignment:
                                CrossAxisAlignment.start,
                                children: [
                                  Image.file(
                                    images[index],
                                    height: 80,
                                    width: 80,
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        images.remove(images[index]);
                                      });
                                    },
                                    child: const Icon(Icons.close),
                                  ),
                                ],
                              );
                            },
                          ),
                        ),
                        DottedBorder(
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              vertical: 25,
                              horizontal: 10,
                            ),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                            ),
                            child: Column(
                              children: [
                                Center(
                                  child: GestureDetector(
                                    onTap: () {
                                      _imgFromGallery();
                                    }, //
                                    child: const Text(
                                      'Upload Files',
                                      style: TextStyle(
                                        decoration: TextDecoration.underline,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),

И результат, который я хочу

1 ответ

Вы не должны звонитьsetStateв вашем цикле попробуйте следующее:

      if (files != null) {
  for (var element in files) {
    images.add(File(element.path));
  }
  setState(() {});
}

Для вашей основной проблемы в сети флаттера вместоImage.fileвам нужно использоватьImage.memory, поэтому сначала измените список результатов пикера на это:

      final picker = ImagePicker();
List<Uint8List> images = [];// <----change this
List<int> imageFiles = [];
void _imgFromGallery() async {
List<XFile>? files = await picker.pickMultiImage(
  imageQuality: 50,
);
if (files != null) {
  for (var element in files) {
    images.add(await element.readAsBytes());// <----change this
  }
  setState(() {});
}

затем покажите это так:

      Image.memory(// <----change this
    images[index],
    height: 80,
    width: 80,
)
Другие вопросы по тегам