Please help on file uploading using Flutter and Laravel - laravel

I'm trying to upload images and other different types of files using Flutter mobile sdk and Laravel api. Here is my Flutter code :
class _MyHomePageState extends State<MyHomePage> {
File _image;
Future getImageGallery() async {
var imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = imageFile;
});
}
Future getImageCamera() async {
var imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = imageFile;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: _image == null
? Text('No image selected')
: Image.file(_image),
),
RaisedButton(
child: Icon(Icons.image),
onPressed: getImageGallery,
),
RaisedButton(
child: Icon(Icons.camera_alt),
onPressed: getImageCamera,
),
RaisedButton(
child: Icon(Icons.file_upload),
onPressed: () {
upload(_image);
},
),
],
),
),
);
}
Future upload(File imageFile) async {
print(imageFile.path);
var stream = http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse('https://api.tredlr.com/api/upload');
var request = http.MultipartRequest('POST', uri);
var multipartFile = http.MultipartFile('image', stream, length,
filename: basename(imageFile.path));
request.files.add(multipartFile);
var response = await request.send();
print(response);
print(response.stream);
print(response.statusCode);
if (response.statusCode == 200) {
print('uploaded');
} else {
print('not uploaded');
}
}
}
and here is my Laravel code :
$photo = $request->file("image");
$ext = $photo->getClientOriginalExtension();
$fileName = rand(10000, 50000) . '.' .$ext;
$thumbSm = 'thumb_sm' . rand(10000, 50000) . '.' .$ext;
$image = Image::make($request->file('image'));
$image->save(base_path().'/public/'. $fileName);
$image->resize(120, 120);
$image->save(base_path().'/public/'. $thumbSm);

Future _test(File file) async {
Dio dio = new Dio();
file.existsSync();
String fileName = file.path.split('/').last;
FormData formData = new FormData.fromMap({
"image": await MultipartFile.fromFile(file.path,filename: fileName)
});
response = await dio.post("http://you ip address/api/route", data: formData);
}

Related

Load image from sharedPreferences to pdf in Flutter

I'm need to load a image from sharedPreferences to a pdf document.
The image loads normally when in normal use, but i don't know how to make it load in the pdf.
When I try to load it like a normal image I get "Unhandled Exception: type 'Image' is not a subtype of type 'PdfImage'"
This is how I use it normally.
import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:MyApp/SharedPrefUtility.dart';
Future<void> initSettings() async {
await Settings.init(
cacheProvider: SharePreferenceCache(),
);
}
class ProfilePage extends StatefulWidget {
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
Image logo;
pickImage(ImageSource source) async {
final _image = await ImagePicker.pickImage(source: ImageSource.gallery);
if (_image != null) {
setState(() {
logo = Image.file(_image);
});
ImageSharedPrefs.saveImageToPrefs(
ImageSharedPrefs.base64String(_image.readAsBytesSync()));
} else {
print('Error picking image!');
}
}
loadImageFromPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final imageKeyValue = prefs.getString(IMAGE_KEY);
if (imageKeyValue != null) {
final imageString = await ImageSharedPrefs.loadImageFromPrefs();
setState(() {
logo = ImageSharedPrefs.imageFrom64BaseString(imageString);
});
}
}
#override
void initState() {
super.initState();
loadImageFromPrefs();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text('Profile Settings'),
),
body: Center(
child: ListView(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ClipRect(
child: Container(
width: 300,
height: 300,
child: logo == null ? Text('No image selected.') : logo,
),
),
RaisedButton(
onPressed: () {
pickImage(ImageSource.gallery);
},
child: Text('Pick Company Logo'),
),
],
),
],
),
),
);
}
}
With SharedPrefUtility.dart
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
const IMAGE_KEY = 'IMAGE_KEY';
class ImageSharedPrefs {
static Future<bool> saveImageToPrefs(String value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return await prefs.setString(IMAGE_KEY, value);
}
static Future<String> loadImageFromPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(IMAGE_KEY);
}
static String base64String(Uint8List data) {
return base64Encode(data);
}
static imageFrom64BaseString(String base64String) {
return Image.memory(
base64Decode(base64String),
fit: BoxFit.contain,
);
}
}
Any Suggestions would be great.
davey06 gave the answer on gitHub
final imageString = await ImageSharedPrefs.loadImageFromPrefs();
// Create a PDF document.
final document = pw.Document();
// Add page to the PDF
document.addPage(pw.Page(build: (context) {
return pw.Center(
child: pw.Image(
PdfImage.file(document.document, bytes: base64Decode(imageString)),
),
);
}));
// Return the PDF file content
return document.save();
https://github.com/DavBfr/dart_pdf/issues/477
"Unhandled Exception: type 'Image' is not a subtype of type 'PdfImage'" - it says you need to convert Image to PdfImage
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
pdf = pw.Document();
PdfImage pdfImage = PdfImage.fromImage(pdf.document, image: logo);
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Image(arcPdfImage, fit: pw.BoxFit.contain);
},
),
);
I'm using images taken from my assets to create PDF in this way:
PdfImage _logo = PdfImage.file(
doc.document,
bytes: (await rootBundle.load('assets/client-logo.png')).buffer.asUint8List(),
);
//later, during widget tree creation
pw.Image(_logo, width: 180);
It's not exactly what you're doing, but I think it's close enough. The PdfImage class can take as input any Uint8List for the bytes argument, so you should be able to use the same input you're using for the base64String method you defined for ImageSharedPrefs

Solve the error or give a Complete working example to upload images with multi image picker as a List<file> with Dio

I am trying to upload images for some days and it's not working so please if you have a working code put it as an answer or just solve the code
Here is the code
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mazadi/Models/ImageUpload.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
class AddAd3 extends StatefulWidget {
AddAd3({
Key key,
}) : super(key: key);
#override
_AddAd3State createState() => _AddAd3State();
}
class _AddAd3State extends State<AddAd3> {
bool _isUploading = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(12.0),
child: ListView(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 100,
height: 100,
child: RaisedButton(
onPressed: () {
getImage();
},
color: Colors.white,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(7.0)),
child: SizedBox(
width: 90,
height: 90,
child: Center(
child: Icon(
Icons.add,
color: Colors.deepOrange,
size: 30.0,
),
),
),
),
),
],
),
SizedBox(
height: 40,
),
SizedBox(
width: 500,
height: 500,
child: _isUploading == true
? FutureBuilder(
future: uploadImage(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Text('loading...');
default:
if (snapshot.hasError)
return new Text('${snapshot.error}');
else
return createListView(context, snapshot);
}
},
)
: Text(""),
),
],
),
));
}
Future getImage() async {
files.clear();
List<Asset> resultList = List<Asset>();
resultList = await MultiImagePicker.pickImages(
maxImages: 10,
enableCamera: false,
);
for (var asset in resultList) {
int MAX_WIDTH = 500; //keep ratio
int height = ((500 * asset.originalHeight) / asset.originalWidth).round();
ByteData byteData =
await asset.getThumbByteData(MAX_WIDTH, height, quality: 80);
if (byteData != null) {
List<int> imageData = byteData.buffer.asUint8List();
MultipartFile u = MultipartFile.fromBytes(
imageData,
filename: asset.name,
);
files.add(u);
}
}
setState(() {
_isUploading = true;
});
}
List<MultipartFile> files = new List<MultipartFile>();
Future<List<String>> uploadImage() async {
FormData formData = new FormData.fromMap({"thumb": files});
Dio dio = new Dio();
var response = await dio.post(
"https://mazadyy.com/index.php?route=api/customer_product/uploadImages",
data: formData);
UploadImage image = UploadImage.fromJson(response.data);
return image.images;
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text("error createListView");
}
if (!snapshot.hasData) {
return Text("");
}
List<String> values = snapshot.data;
return new ListView.builder(
shrinkWrap: true,
itemCount: values.length,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[
Image.network(
values[index],
width: 300,
height: 100,
),
SizedBox(
height: 40,
),
],
);
},
);
}
}
and here it the model
class UploadImage {
List<String> images;
UploadImage({this.images});
factory UploadImage.fromJson(Map<String, dynamic> json) {
return UploadImage(images: parseImage(json['images']));
}
static List<String> parseImage(json) {
return new List<String>.from(json);
}
}
the exception that I get is
type String is not a subtype of 'Map<String, dynamic>'
so if you solved the error I will really appreciate it and give him 50 reputation as a reward because
I saw many struggle with the same problem
any help will be appreciated whatever it's
if (images.isEmpty || images[0] != null) {
for (int i = 0; i < images.length; i++) {
ByteData byteData = await images[i].getByteData();
List<int> imageData = byteData.buffer.asUint8List();
http.MultipartFile multipartFile =
http.MultipartFile.fromBytes('image', imageData,
filename: images[i].name,
contentType: MediaType('image', 'jpg'));
imagestoEdit.add(multipartFile);
print(imagestoEdit.length);
}
}
Dio.post(url,formdata:{images:imagestoEdit})

Flutter Save & Load Image - Image Picker/Image crop

I'm trying to make a profile picture screen in flutter. I have used this 2 plugin (image crop and image picker) for select and edit the image.
class ProfilePage extends StatefulWidget {
#override
__ProfilePageState createState() => __ProfilePageState();
}
class __ProfilePageState extends State<ProfilePage> {
File _pickedImage;
String _imagepath;
#override
void initState() {
super.initState();
LoadImage();
}
#override
Widget build(BuildContext context) {
return Scaffold(
// appBar: AppBar(
// title: Text('Profile'),
// ),
body: ListView(
children: <Widget>[
Center(
child: CircleAvatar(
radius: 80,
child: _imagepath == null ? Text('Profile image') : null,
backgroundImage:
_imagepath != null ? FileImage(File(_imagepath)) : null,
),
),
SizedBox(height: 10),
RaisedButton(
child: Text('Select image'),
onPressed: () {
_showPickOptionDialog(context);
},
)
],
),
);
}
_loadPicker(ImageSource source) async {
File picked = await ImagePicker.pickImage(source: source);
if (picked != null) {
_cropImage(picked);
SaveImage(picked.path);
}
LoadImage();
Navigator.pop(context);
}
_cropImage(File picked) async {
File cropped = await ImageCropper.cropImage(
androidUiSettings: AndroidUiSettings(
toolbarTitle: "Modifica immagine",
statusBarColor: Colors.green,
toolbarColor: Colors.green,
toolbarWidgetColor: Colors.white,
),
sourcePath: picked.path,
// aspectRatioPresets: [
// CropAspectRatioPreset.original,
// CropAspectRatioPreset.ratio16x9,
// CropAspectRatioPreset.ratio4x3,
// ],
maxWidth: 800,
);
if (cropped != null) {
setState(() {
_pickedImage = cropped;
});
}
}
void _showPickOptionDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text('select image from gallery'),
onTap: () {
_loadPicker(ImageSource.gallery);
}),
ListTile(
title: Text('Scatta una foto'),
onTap: () {
_loadPicker(ImageSource.camera);
},
),
],
),
));
}
void SaveImage(path) async {
SharedPreferences saveimage = await SharedPreferences.getInstance();
saveimage.setString("imagepath", path);
}
void LoadImage() async {
SharedPreferences saveimage = await SharedPreferences.getInstance();
setState(() {
_imagepath = saveimage.getString("imagepath");
});
}
}
Code works but it only save the picked image instead of the cropped one.
I've tried many times but I can't see the error, sorry about that..
could you help me?
Thanks!
when you use Future you should return value and use this value with .then()
try this:
class ProfilePage extends StatefulWidget {
#override
__ProfilePageState createState() => __ProfilePageState();
}
class __ProfilePageState extends State<ProfilePage> {
File _pickedImage;
String _imagepath;
#override
void initState() {
super.initState();
LoadImage();
}
#override
Widget build(BuildContext context) {
return Scaffold(
// appBar: AppBar(
// title: Text('Profile'),
// ),
body: ListView(
children: <Widget>[
Center(
child: CircleAvatar(
radius: 80,
child: _imagepath == null ? Text('Profile image') : null,
backgroundImage:
_imagepath != null ? FileImage(File(_imagepath)) : null,
),
),
SizedBox(height: 10),
RaisedButton(
child: Text('Select image'),
onPressed: () {
_showPickOptionDialog(context);
},
)
],
),
);
}
_loadPicker(ImageSource source) async {
File picked = await ImagePicker.pickImage(source: source);
if (picked != null) {
_cropImage(picked).then(File cropped){
SaveImage(cropped.path);
}
}
LoadImage();
Navigator.pop(context);
}
Future<File> _cropImage(File picked) async {
File cropped = await ImageCropper.cropImage(
androidUiSettings: AndroidUiSettings(
toolbarTitle: "Modifica immagine",
statusBarColor: Colors.green,
toolbarColor: Colors.green,
toolbarWidgetColor: Colors.white,
),
sourcePath: picked.path,
// aspectRatioPresets: [
// CropAspectRatioPreset.original,
// CropAspectRatioPreset.ratio16x9,
// CropAspectRatioPreset.ratio4x3,
// ],
maxWidth: 800,
);
if (cropped != null) {
setState(() {
_pickedImage = cropped;
});
}
return cropped;
}
void _showPickOptionDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text('select image from gallery'),
onTap: () {
_loadPicker(ImageSource.gallery);
}),
ListTile(
title: Text('Scatta una foto'),
onTap: () {
_loadPicker(ImageSource.camera);
},
),
],
),
));
}
void SaveImage(path) async {
SharedPreferences saveimage = await SharedPreferences.getInstance();
saveimage.setString("imagepath", path);
}
void LoadImage() async {
SharedPreferences saveimage = await SharedPreferences.getInstance();
setState(() {
_imagepath = saveimage.getString("imagepath");
});
}
}
Found the solution by editing this part:
if (cropped != null) {
_pickedImage = cropped;
SaveImage(_pickedImage.path);
LoadImage();
setState(() {});
}
}

replacing image in file manager does not replace the image in app

I uploaded an image on firebase storage. and to access said image on my flutter app, I first download it to the device and then use FileImage to display the image. However, if the image is changed, it still displays the previous one... Here's my code
var error;
Future getImage() async {
try {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
);
await FirebaseStorage.instance
.ref()
.child(userMap['uid'])
.putFile(image)
.onComplete;
await FirebaseStorage.instance
.ref()
.child(userMap['uid'])
.writeToFile(File(path))
.future;
setState(() {
profile = FileImage(File(path));
});
} catch (e) {
error = e;
}
}
The following code displays the image...
GestureDetector(
onTap: () {
getImage();
},
child: CircleAvatar(
child: Icon(
Icons.add_a_photo,
color: color2.withOpacity(0.5),
),
radius: widget.height * 0.05,
backgroundColor: color3,
backgroundImage: profile,
),
),
please help
I could recommend you another way to solve your issue.
First thing, you don't need to use FileImage because it's very difficult control you cache
with it.
Try the next code:
Future<String> uploadImage(File image) async {
var reference = FirebaseStorage.insance.ref().child(userMap['uid']);
var uploadTask = reference.putFile(image); // you can just put your file like that
var snapshot = await uploadTask.onComplete;
var location = await snapshot.ref.getDownloadURL(); // and get url with it with this code
return location.toString()
}
Future getImage() async {
try {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
);
profile = await uploadImage(image)
setState((){});
}
catch (e) {
error = e;
}
}
after you get your url address with uploadImage, please use library: https://pub.dev/packages/cached_network_image. It's perfect for work with images.
GestureDetector(
onTap: () {
getImage();
},
child: CircleAvatar(
child: Icon(
Icons.add_a_photo,
color: color2.withOpacity(0.5),
),
radius: widget.height * 0.05,
backgroundColor: color3,
backgroundImage: CachedNetworkImageProvider(
imageUrl: profile,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
),

How can I select and upload Multiple images in Flutter

I tried to find how to select and upload multiple images in flutter but most of the plugins are not working or I did not understand them well. I found little application but it selects and upload only one picture. How to change this code that user can select and upload multiple pictures or is there any other alternatives. Please write in details, i am freshman in coding. Thanks in advance.
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:mime/mime.dart';
import 'dart:convert';
import 'package:http_parser/http_parser.dart';
import 'package:toast/toast.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Image Upload Demo',
theme: ThemeData(primarySwatch: Colors.pink),
home: ImageInput());
}
}
class ImageInput extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _ImageInput();
}
}
class _ImageInput extends State<ImageInput> {
// To store the file provided by the image_picker
File _imageFile;
// To track the file uploading state
bool _isUploading = false;
String baseUrl = 'http://YOUR_IPV4_ADDRESS/flutterdemoapi/api.php';
void _getImage(BuildContext context, ImageSource source) async {
File image = await ImagePicker.pickImage(source: source);
setState(() {
_imageFile = image;
});
// Closes the bottom sheet
Navigator.pop(context);
}
Future<Map<String, dynamic>> _uploadImage(File image) async {
setState(() {
_isUploading = true;
});
// Find the mime type of the selected file by looking at the header bytes of the file
final mimeTypeData =
lookupMimeType(image.path, headerBytes: [0xFF, 0xD8]).split('/');
// Intilize the multipart request
final imageUploadRequest =
http.MultipartRequest('POST', Uri.parse(baseUrl));
// Attach the file in the request
final file = await http.MultipartFile.fromPath('image', image.path,
contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
// Explicitly pass the extension of the image with request body
// Since image_picker has some bugs due which it mixes up
// image extension with file name like this filenamejpge
// Which creates some problem at the server side to manage
// or verify the file extension
imageUploadRequest.fields['ext'] = mimeTypeData[1];
imageUploadRequest.files.add(file);
try {
final streamedResponse = await imageUploadRequest.send();
final response = await http.Response.fromStream(streamedResponse);
if (response.statusCode != 200) {
return null;
}
final Map<String, dynamic> responseData = json.decode(response.body);
_resetState();
return responseData;
} catch (e) {
print(e);
return null;
}
}
void _startUploading() async {
final Map<String, dynamic> response = await _uploadImage(_imageFile);
print(response);
// Check if any error occured
if (response == null || response.containsKey("error")) {
Toast.show("Image Upload Failed!!!", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
} else {
Toast.show("Image Uploaded Successfully!!!", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
}
}
void _resetState() {
setState(() {
_isUploading = false;
_imageFile = null;
});
}
void _openImagePickerModal(BuildContext context) {
final flatButtonColor = Theme.of(context).primaryColor;
print('Image Picker Modal Called');
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Container(
height: 150.0,
padding: EdgeInsets.all(10.0),
child: Column(
children: <Widget>[
Text(
'Pick an image',
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(
height: 10.0,
),
FlatButton(
textColor: flatButtonColor,
child: Text('Use Camera'),
onPressed: () {
_getImage(context, ImageSource.camera);
},
),
FlatButton(
textColor: flatButtonColor,
child: Text('Use Gallery'),
onPressed: () {
_getImage(context, ImageSource.gallery);
},
),
],
),
);
});
}
Widget _buildUploadBtn() {
Widget btnWidget = Container();
if (_isUploading) {
// File is being uploaded then show a progress indicator
btnWidget = Container(
margin: EdgeInsets.only(top: 10.0),
child: CircularProgressIndicator());
} else if (!_isUploading && _imageFile != null) {
// If image is picked by the user then show a upload btn
btnWidget = Container(
margin: EdgeInsets.only(top: 10.0),
child: RaisedButton(
child: Text('Upload'),
onPressed: () {
_startUploading();
},
color: Colors.pinkAccent,
textColor: Colors.white,
),
);
}
return btnWidget;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Upload Demo'),
),
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 40.0, left: 10.0, right: 10.0),
child: OutlineButton(
onPressed: () => _openImagePickerModal(context),
borderSide:
BorderSide(color: Theme.of(context).accentColor, width: 1.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.camera_alt),
SizedBox(
width: 5.0,
),
Text('Add Image'),
],
),
),
),
_imageFile == null
? Text('Please pick an image')
: Image.file(
_imageFile,
fit: BoxFit.cover,
height: 300.0,
alignment: Alignment.topCenter,
width: MediaQuery.of(context).size.width,
),
_buildUploadBtn(),
],
),
);
}
}
I used that package:
dependencies:
multi_image_picker: ^4.6.7
Ex:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:multi_image_picker/multi_image_picker.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Asset> images = List<Asset>();
String _error;
#override
void initState() {
super.initState();
}
Widget buildGridView() {
if (images != null)
return GridView.count(
crossAxisCount: 3,
children: List.generate(images.length, (index) {
Asset asset = images[index];
return AssetThumb(
asset: asset,
width: 300,
height: 300,
);
}),
);
else
return Container(color: Colors.white);
}
Future<void> loadAssets() async {
setState(() {
images = List<Asset>();
});
List<Asset> resultList;
String error;
try {
resultList = await MultiImagePicker.pickImages(
maxImages: 300,
);
} on Exception catch (e) {
error = e.toString();
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
images = resultList;
if (error == null) _error = 'No Error Dectected';
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Center(child: Text('Error: $_error')),
RaisedButton(
child: Text("Pick images"),
onPressed: loadAssets,
),
Expanded(
child: buildGridView(),
)
],
),
),
);
}
}
Add dependecy of image_picker:
image_picker: ^0.8.4+3
Then make a method for selectImages():
final ImagePicker imagePicker = ImagePicker();
List<XFile>? imageFileList = [];
void selectImages() async {
final List<XFile>? selectedImages = await
imagePicker.pickMultiImage();
if (selectedImages!.isNotEmpty) {
imageFileList!.addAll(selectedImages);
}
print("Image List Length:" + imageFileList!.length.toString());
setState((){});
}
Create a builder for showing selected Images:
return Scaffold(
appBar: AppBar(
title: Text('Multiple Images'),
),
body: SafeArea(
child: Column(
children: [
ElevatedButton(
onPressed: () {
selectImages();
},
child: Text('Select Images'),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
itemCount: imageFileList!.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return Image.file(File(imageFileList![index].path),
fit: BoxFit.cover,);
}),
),
),
],
),
));
Complete Source code available in github link...
https://github.com/NishaJain24/multi_image_picker

Resources