اذهب إلى المحتوى
  • 0

كيفية الاحتفاط بصور السابقه في image_picker

Flutter Dev

السؤال

تحيه طيبه للجميع

انا استعمل المكتبه التاليه : image_picker لختيار مجموعة من الصور في وقت واحد بستخدام :

 // Pick multiple images
    final List<XFile>? images = await _picker.pickMultiImage();

الكود يعمل بشكل ممتاز ولكن المشكله مثلا لو قمت باختيار 3 صور في اول مره بعدها رغبة باضافة المزيد لو قمت باضافة المزيد سوف يتم حذف الصور السابقه التي سبق وتم اختيارها ووضع الصور الجديده فقط مكانها 

كيف يمكن الاحتفاظ بصور السابقه في حالة اضافة صور جديده لها ياليت اذا احد واجه هذا المشكله ويعرف طريقة لحلها يفيدنا بارك الله فيكم

 

الكود كامل:


import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Picker Demo',
      home: MyHomePage(title: 'Image Picker Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<XFile> _imageFileList;

  set _imageFile(XFile value) {
    _imageFileList = value == null ? null : [value];
  }

  dynamic _pickImageError;
  bool isVideo = false;
  final ImagePicker _picker = ImagePicker();


  void _onImageButtonPressed(ImageSource source,
      {BuildContext context, bool isMultiImage = false}) async {
   if (isMultiImage) {

            try {
              final pickedFileList = await _picker.pickMultiImage(
                maxWidth: 66,
                maxHeight: 66,
                imageQuality: 66,
              );
              setState(() {
                _imageFileList = pickedFileList;
              });
            } catch (e) {
              setState(() {
                _pickImageError = e;
              });
            }



    }
  }





  Widget _previewImages() {


    if (_imageFileList != null) {
      return Semantics(
          child: ListView.builder(
            key: UniqueKey(),
            itemBuilder: (context, index) {
              return Semantics(
                label: 'image_picker_example_picked_image',
                child: kIsWeb
                    ? Image.network(_imageFileList[index].path)
                    : Image.file(File(_imageFileList[index].path)),
              );
            },
            itemCount: _imageFileList.length,
          ),
          label: 'image_picker_example_picked_images');
    } else if (_pickImageError != null) {
      return Text(
        'Pick image error: $_pickImageError',
        textAlign: TextAlign.center,
      );
    } else {
      return const Text(
        'You have not yet picked an image.',
        textAlign: TextAlign.center,
      );
    }
  }


  Future<void> retrieveLostData() async {
    final LostDataResponse response = await _picker.retrieveLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      if (response.type == RetrieveType.video) {
        isVideo = true;

      } else {
        isVideo = false;
        setState(() {
          _imageFile = response.file;
          _imageFileList = response.files;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: !kIsWeb && defaultTargetPlatform == TargetPlatform.android
            ? FutureBuilder<void>(
          future: retrieveLostData(),
          builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return const Text(
                  'You have not yet picked an image.',
                  textAlign: TextAlign.center,
                );
              case ConnectionState.done:
                return _previewImages();
              default:
                if (snapshot.hasError) {
                  return Text(
                    'Pick image/video error: ${snapshot.error}}',
                    textAlign: TextAlign.center,
                  );
                } else {
                  return const Text(
                    'You have not yet picked an image.',
                    textAlign: TextAlign.center,
                  );
                }
            }
          },
        )
            : _previewImages(),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[

          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              onPressed: () {
                isVideo = false;
                _onImageButtonPressed(
                  ImageSource.gallery,
                  context: context,
                  isMultiImage: true,
                );
              },
              heroTag: 'image1',
              tooltip: 'Pick Multiple Image from gallery',
              child: const Icon(Icons.photo_library),
            ),
          ),



        ],
      ),
    );
  }




}

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 1
بتاريخ 1 دقيقة مضت قال مروان مروان3:

تم وضع الكود بشكل التالي :

لنحاول التعديل:

try {
  final pickedFileList = await _picker.pickMultiImage(
    maxWidth: 66,
    maxHeight: 66,
    imageQuality: 66,
  );
	
  if (_imageFileList == null) {
   if ( pickedFileList == null)
    return;
    setState(() {
           _imageFileList =pickedFileList;
	});
  }
  else {
  	if (pickedFileList != null) {
      setState(() {
             _imageFileList = [..._imageFileList, ...pickedFileList].toSet().toList();
      });
    }
  // لا تغيير
  }
  
  
} catch (e) {
  setState(() {
           _pickImageError = e;
   });
}

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 1

تريد الإضافة.. لربما اختار المستخدم نفس الصورة السابقة سوف تتكرر. سوف ندمج القائمة السابقة مع التحديد الجديد (القائمة الجديدة) بدون تكرار

setState(() {
	_imageFileList = (_imageFileList + pickedFileList).toSet().toList();
});

الطريقة toSet تقوم بعمل مجموعة من القائمة، والمجموعة هي عناصر غير مكررة، سندمج القائمتين، ونعيد من الناتج مجموعة، ثم نحولها إلى قائمة..

الطريقة + تدمج سلسلتين في Dart 2، طريقة ثانية:

final tmp = new List.from(_imageFileList)..addAll(pickedFileList);

final tmp2 = tmp.toSet().toList();

setState(() {
	_imageFileList = tmp2;
});

 

Dart الأقدم تستخدم addAll 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 1
بتاريخ الآن قال مروان مروان3:

قمت بتطبيق الطريقة الاولى ولكن يظهر لدي المشكله التاليه مرفق صوره :

أعتقد أن القائمة الأولى فارغة

جرب التالي:

setState(() {
	_imageFileList = [..._imageFileList, ...pickedFileList].toSet().toList();
});

++ اختبر أن القائمة الجديدة ليست فارغة

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 1
بتاريخ الآن قال مروان مروان3:

الف شكر لك يا اخوي ربي يزيدك ويبارك لك علمك من واسع فضله 

تمام،

الشرح: اختبار كل حالات القائمتين (فارغة أو غير فارغة + فارغة أو غير فارغة) عن طريق if else

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0
بتاريخ 7 دقائق مضت قال Wael Aljamal:

تريد الإضافة.. لربما اختار المستخدم نفس الصورة السابقة سوف تتكرر. سوف دمج القائمة السابقة مع التحديد الجديد بدون تكرار


setState(() {
	_imageFileList = (_imageFileList + pickedFileList).toSet().toList();
});

الطريقة toSet تقوم بعمل مجموعة من القائمة، والمجموعة هي عناصر غير مكررة، سندمج القائمتين، ونعيد من الناتج مجموعة، ثم نحولها إلى قائمة..

الطريقة + تدمج سلسلتين في Dart 2، طريقة ثانية:


final tmp = new List.from(_imageFileList)..pickedFileList(list2);

setState(() {
	_imageFileList = tmp;
});

 

اهلا بك اخي الكريم 

قمت بتطبيق الطريقة الاولى ولكن يظهر لدي المشكله التاليه مرفق صوره :

device-2021-10-12-232429.thumb.png.86e03e0d9d11bc01f7ec27b0973b51b5.png

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0
بتاريخ 15 دقائق مضت قال Wael Aljamal:

أعتقد أن القائمة الأولى فارغة

جرب التالي:


setState(() {
	_imageFileList = [..._imageFileList, ...pickedFileList].toSet().toList();
});

++ اختبر أن القائمة الجديدة ليست فارغة

اهلا اخي 

تم وضع الكود بشكل التالي :

  void _onImageButtonPressed(ImageSource source,
      {BuildContext context, bool isMultiImage = false}) async {
   if (isMultiImage) {

            try {
              final pickedFileList = await _picker.pickMultiImage(
                maxWidth: 66,
                maxHeight: 66,
                imageQuality: 66,
              );

              setState(() {
                _imageFileList = [..._imageFileList, ...pickedFileList].toSet().toList();
              });
            } catch (e) {
              setState(() {
                _pickImageError = e;
              });
            }



    }
  }

 

وقد حصل الخطاء التالي:

 

11.thumb.png.45f21d4624bc192ea097bc8277043589.png

 

بتاريخ 29 دقائق مضت قال Wael Aljamal:

تريد الإضافة.. لربما اختار المستخدم نفس الصورة السابقة سوف تتكرر. سوف ندمج القائمة السابقة مع التحديد الجديد (القائمة الجديدة) بدون تكرار


setState(() {
	_imageFileList = (_imageFileList + pickedFileList).toSet().toList();
});

الطريقة toSet تقوم بعمل مجموعة من القائمة، والمجموعة هي عناصر غير مكررة، سندمج القائمتين، ونعيد من الناتج مجموعة، ثم نحولها إلى قائمة..

الطريقة + تدمج سلسلتين في Dart 2، طريقة ثانية:


final tmp = new List.from(_imageFileList)..addAll(pickedFileList);

final tmp2 = tmp.toSet().toList();

setState(() {
	_imageFileList = tmp2;
});

 

Dart الأقدم تستخدم addAll 

ايضا قمت تبطبيق هذا الامر :

void _onImageButtonPressed(ImageSource source,
      {BuildContext context, bool isMultiImage = false}) async {
   if (isMultiImage) {

            try {
              final pickedFileList = await _picker.pickMultiImage(
                maxWidth: 66,
                maxHeight: 66,
                imageQuality: 66,
              );

              final tmp = new List.from(_imageFileList)..addAll(pickedFileList);

              final tmp2 = tmp.toSet().toList();

              setState(() {
                _imageFileList = tmp2;
              });
            } catch (e) {
              setState(() {
                _pickImageError = e;
              });
            }



    }
  }

وقد حصلت على خطاء مشابه للكود السابق

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0
بتاريخ 4 دقائق مضت قال Wael Aljamal:

لنحاول التعديل:


try {
  final pickedFileList = await _picker.pickMultiImage(
    maxWidth: 66,
    maxHeight: 66,
    imageQuality: 66,
  );
	
  if (_imageFileList == null) {
   if ( pickedFileList == null)
    return;
    setState(() {
           _imageFileList =pickedFileList;
	});
  }
  else {
  	if (pickedFileList != null) {
      setState(() {
             _imageFileList = [..._imageFileList, ...pickedFileList].toSet().toList();
      });
    }
  // لا تغيير
  }
  
  
} catch (e) {
  setState(() {
           _pickImageError = e;
   });
}

 

الف شكر لك يا اخوي ربي يزيدك ويبارك لك علمك من واسع فضله 

 

الكود كامل بعد التعديل للفائده


import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Picker Demo',
      home: MyHomePage(title: 'Image Picker Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<XFile> _imageFileList;

  set _imageFile(XFile value) {
    _imageFileList = value == null ? null : [value];
  }

  dynamic _pickImageError;
  bool isVideo = false;
  final ImagePicker _picker = ImagePicker();


  void _onImageButtonPressed(ImageSource source,
      {BuildContext context, bool isMultiImage = false}) async {
    if (isMultiImage) {
      try {
        final pickedFileList = await _picker.pickMultiImage(
          maxWidth: 66,
          maxHeight: 66,
          imageQuality: 66,
        );

        if (_imageFileList == null) {
          if (pickedFileList == null)
            return;
          setState(() {
            _imageFileList = pickedFileList;
          });
        }
        else {
          if (pickedFileList != null) {
            setState(() {
              _imageFileList =
                  [..._imageFileList, ...pickedFileList].toSet().toList();
            });
          }
          // لا تغيير
        }
      } catch (e) {
        setState(() {
          _pickImageError = e;
        });
      }
    }
  }



  Widget _previewImages() {


    if (_imageFileList != null) {
      return Semantics(
          child: ListView.builder(
            key: UniqueKey(),
            itemBuilder: (context, index) {
              return Semantics(
                label: 'image_picker_example_picked_image',
                child: kIsWeb
                    ? Image.network(_imageFileList[index].path)
                    : Image.file(File(_imageFileList[index].path)),
              );
            },
            itemCount: _imageFileList.length,
          ),
          label: 'image_picker_example_picked_images');
    } else if (_pickImageError != null) {
      return Text(
        'Pick image error: $_pickImageError',
        textAlign: TextAlign.center,
      );
    } else {
      return const Text(
        'You have not yet picked an image.',
        textAlign: TextAlign.center,
      );
    }
  }


  Future<void> retrieveLostData() async {
    final LostDataResponse response = await _picker.retrieveLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      if (response.type == RetrieveType.video) {
        isVideo = true;

      } else {
        isVideo = false;
        setState(() {
          _imageFile = response.file;
          _imageFileList = response.files;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: !kIsWeb && defaultTargetPlatform == TargetPlatform.android
            ? FutureBuilder<void>(
          future: retrieveLostData(),
          builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return const Text(
                  'You have not yet picked an image.',
                  textAlign: TextAlign.center,
                );
              case ConnectionState.done:
                return _previewImages();
              default:
                if (snapshot.hasError) {
                  return Text(
                    'Pick image/video error: ${snapshot.error}}',
                    textAlign: TextAlign.center,
                  );
                } else {
                  return const Text(
                    'You have not yet picked an image.',
                    textAlign: TextAlign.center,
                  );
                }
            }
          },
        )
            : _previewImages(),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[

          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              onPressed: () {
                isVideo = false;
                _onImageButtonPressed(
                  ImageSource.gallery,
                  context: context,
                  isMultiImage: true,
                );
              },
              heroTag: 'image1',
              tooltip: 'Pick Multiple Image from gallery',
              child: const Icon(Icons.photo_library),
            ),
          ),



        ],
      ),
    );
  }




}

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...