Image Picker not opening after asking permission on Android in flutter. [Wokring fine on IOS] - image

I am using a Cupertino switch for picking image from gallery. First time when user clicks it ask for permission. After getting the permission the imagePicker never opens the gallery. when i click the button again it shows
Image picker already active. If i close the app and open again it works fine. I have tried:
1. Flutter clean , flutter run
2. Upgrading the dependencies
Nothing works.
here is my code:
Widget _rightSectionPhoto() {
return new Container(
child: CupertinoSwitch(
value: isSwitchedforidPic,
onChanged: isSwitchedforidPicStatus
? (value) {
if (value == true) {
setState(() {
isSwitchedforidStatus = false;
getImage();
});
} else {
setState(() {
isImageUploaded = false;
});
}
}
: null,
activeColor: Colors.deepOrangeAccent,
),
);
}
And here is getImage function
Future getImage() async {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 10,
);
if (image == null) {
setState(() {
isSwitchedforidPic = false;
isSwitchedforidStatus = true;
isImageUploaded = false;
});
} else {
List<int> imageBytes = await image.readAsBytes();
base64Image = base64Encode(imageBytes);
setState(() {
isImageUploaded = true;
});
}
}

Related

how to upload images in server using flutter and laravel api?

How to upload images in server using flutter with Laravel API? I tried using getx, its returning null. also I have image_picker and image_cropper package in my pubspec.yaml
Select Image from Gallery using File Picker
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
class ImageScreen extends StatefulWidget {
ImageScreen();
#override
State<ImageScreen> createState() => _ImageScreenState();
}
class _ImageScreenState extends State<ImageScreen> {
File file;
Future<File> uploadImage() async {
FilePickerResult result = await FilePicker.platform.pickFiles();
if (result != null) {
setState(() {
file = File(result.files.single.path);
});
print(result.files.single.path);
} else {
// User canceled the picker
}
return file;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
onTap: () {
uploadImage();
},
child: Container(
color: Colors.green,
padding: EdgeInsets.all(5),
child: Text('Upload Image', style: TextStyle(fontSize: 16, color: Colors.white),)
),
),
);
}
}
Uploading Image to the server using http.multipartFile
static Future<dynamic> uploadImage({File file}) async {
try {
http.MultipartRequest request = new http.MultipartRequest("POST", _uri);
http.MultipartFile multipartFile = await http.MultipartFile.fromPath('file_name', file.path);
request.files.add(multipartFile);
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
if (response.statusCode == 200 ) {
return jsonDecode(response.body);
}
}
catch (e) {
return null;
}
}
final images = <File>[].obs;
Use this method for picking up images
Future pickImage(ImageSource source) async {
ImagePicker imagePicker = ImagePicker();
XFile pickedFile = await imagePicker.pickImage(source: source, imageQuality: 80);
File imageFile = File(pickedFile.path);
print(imageFile);
if (imageFile != null) {
images.add(imageFile);
} else {
Get.showSnackbar(GetSnackBar(message: "Please select an image file"));
}
}
Use this for uploading images to the server with your specific url.As I have used dio for uploading.You can use http as well.
Future<String> uploadImage(File file) async {
String fileName = file.path.split('/').last;
// you can edit it for your own convenience
var _queryParameters = {
'api_token': 'your token if required',
};
Uri _uri = 'Your base url'
var formData = FormData.fromMap({
"file": await MultipartFile.fromFile(file.path, filename: fileName),
});
var response = await dio.post(_uri, data: formData);
print(response.data);
if (response.data['data'] != false) {
return response.data['data'];
} else {
throw new Exception(response.data['message']);
}
}
This works for me, so maybe others might need it as well.
uploadImage(imageFile) async {
var stream = new http.ByteStream(
DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(
'http://192.168.5.196/ApiFileUploadTest/public/api/uploading-file-api');
var request = new http.MultipartRequest('POST', uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}

flutter visibility error and initState problem

i'm a beginner and i have a strange errori got a problem in visibility i work with laravel api if i have no products in database this.widget.client always false , if i have a product in database the application works perfectly !!
flutter code :
bool client=false ;
_getAuthenticatedUser() async {
SharedPreferences _prefs = await SharedPreferences.getInstance();
var log = new Logger();
var x = _prefs.getString('photoUser');
this.widget.photo=json.decode(x);
this.widget.name= json.decode(_prefs.getString('Username'));
if(_prefs.getString('token')!=null){
if(json.decode(_prefs.getString('role'))=='superAdmin'){
this.widget.superAdmin=true;}else{this.widget.superAdmin=false;}
if(json.decode(_prefs.getString('role'))=='admin'){
this.widget.admin=true;
}else{this.widget.admin=false;}
if(json.decode(_prefs.getString('role'))=='user'){
_prefs.setString('client', 'client');
this.widget.client=true;
}else{this.widget.client=false; log.d('here not client');}
}
else{
this.widget.superAdmin=false;
this.widget.admin=false;
this.widget.client=false;
}
}
_getAllProducts() async {
var _productService = ProductService();
var products = await _productService.getProducts();
var result = json.decode(products.body);
var log = new Logger();
_productList.clear();
result.forEach((data) {
var product = Product();
product.id = data['id'] ?? 0 ;
product.name = data['name'] ?? "";
product.photo = data['photo'] ?? "";
product.price = data['price'] ?? 0;
product.discount = data['discount'] ?? 0;
product.detail = data['detail'] ?? 'No detail';
product.quantity = data['quantity'] ?? 0;
setState(() {
_productList.add(product);
});
});
}
#override
void initState(){
super.initState();
_getAuthenticatedUser();
_getAllProducts();}
and in the build
Visibility(
visible: this.widget.client,
child: ListTile(
leading: Icon(Icons.category,color: Colors.white,),
title: Text('Produits refusé',style: TextStyle(color: Colors.white)),
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) =>RefusedProducts(_refusedProductList,this.widget.client,this.widget.photo,this.widget.name)));
}
),),
You can wrap your setState() function like this:
WidgetsBinding.instance?.addPostFrameCallback((_) {
setState(() {
_productList.add(product);
});
});

Flutter: How do I select and display images

I cannot display selected images from gallery in a grid. In this code, I am displaying images in a list and I want to turn it into small grid type in 1 row but I don't know how. Can you please help?
Here's my code for selecting multiple images using file picker.
FileType fileType;
String imgName, _imgPath;
Map<String, String> imgPaths;
List<File> _imgList = List();
bool isLoadingPath = false;
_openFile() async {
setState(() => isLoadingPath = true);
try {
_imgPath = null;
imgPaths = await FilePicker.getMultiFilePath(
type: fileType != null ? fileType : FileType.custom,
allowedExtensions: ['jpg', 'png']);
_imgList.clear();
imgPaths.forEach((key, val) {
print('{ key: $key, value: $val}');
File file = File(val);
_imgList.add(file);
});
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
setState(() {
isLoadingPath = false;
imgName = _imgPath != null
? _imgPath.split('/').last
: imgPaths != null
? imgPaths.keys.toString()
: '...';
});
}
Displaying images in a list. (How to display images as it is?)
Widget _fileBuilder() {
return Builder(
builder: (BuildContext context) => isLoadingPath
? Padding(
padding: const EdgeInsets.only(bottom: 4.0))
: _imgPath != null || imgPaths != null && (imgPaths.length > 1 && imgPaths.length < 5)
? new Container(
height: imgPaths.length > 1
? MediaQuery.of(context).size.height * 0.15
: MediaQuery.of(context).size.height * 0.10,
width: MediaQuery.of(context).size.width,
child: new Scrollbar(
child: new ListView.separated(
itemCount: imgPaths != null && imgPaths.isNotEmpty
? imgPaths.length
: 1,
itemBuilder: (BuildContext context, int index) {
final bool isMultiPath = imgPaths != null && imgPaths.isNotEmpty;
final int fileNo = index + 1;
final String name = 'File $fileNo : ' + (isMultiPath
? imgPaths.keys.toList()[index]
: _imgPath ?? '...');
final filePath = isMultiPath
? imgPaths.values.toList()[index].toString()
: _imgPath;
return new ListTile(
title: Transform.translate(
offset: Offset(-25, 0),
child: new Text(
name,
),
),
leading: Icon(Icons.attach_file_outlined, color: Color(0xFFF3A494),),
dense: true,
);
},
separatorBuilder:
(BuildContext context, int index) =>
new Divider(),
)),
)
: new Container(child: Text('4 photos is the maximum'),),
);
}
Dependencies:
file_picker: ^1.4.2
path:
mime:
async:
what you can do is, use the Image Picker dependency. You can find its documentation on pub.dev. after installing it, try using it and store the image uploaded in a file in the device. and with that file name, you can access the image.
You can try the below code, it worked for me. Also don't forget to import dart:io; for using file.
var _storedImage;
Future<void> _takePictureByCamera() async {
final picker = ImagePicker();
final imageFile =
await picker.getImage(source: ImageSource.camera, maxWidth: 600, imageQuality: 60);
setState(() {
_storedImage = File(imageFile!.path);
});
final appDir = await path_provider.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile!.path);
final savedImage = File(imageFile.path).copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
Future<void> _takePictureByGallery() async {
final picker = ImagePicker();
final imageFile =
await picker.getImage(source: ImageSource.gallery, maxWidth: 600);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = File(imageFile.path);
});
final appDir = await path_provider.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = File(imageFile.path).copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
and after selecting or clicking the image, you can do this to display the image ->
void getImage() async {
final pickedImage = await showModalBottomSheet(
context: accountTabScaffoldMessengerKey.currentContext!,
backgroundColor: Colors.transparent,
enableDrag: true,
// elevation: 0,
builder: (context) => AccountImageUpdateBottomSheet(_selectImage),
);
_selectImage(pickedImage);
}
void _selectImage(File pickedImage) {
setState(() {
_pickedImage = pickedImage;
});
}
The image you selected is stored in the _pickedImage and you can access it by Image.file(_pickedImage).

Flutter web image_picker no implementation found

I am using version 0.6.7+22 of the image_picker Flutter package to pick an image from the device in my Flutter web app. I call getImage function in a pop-up:
class _ImageVerificationPopUpState extends State<ImageVerificationPopUp> {
File _image;
final picker = ImagePicker();
#override
Widget build(BuildContext context) {
return AlertDialog(
title: Text("Upload screenshot"),
content: SizedBox(
width: MediaQuery.of(context).size.width * 0.3,
child: Center(
child: _image != null
? SelectedImage(kIsWeb ? Image.network(_image.path) : Image.file(_image), () {
setState(() {
_image = null;
});
})
: SelectImageButton(_getImage),
),
),
actions: [
TextButton(onPressed: () => Navigator.of(context).pop(), child: Text("Cancel")),
TextButton(
onPressed: () {
final ImageCubit imageCubit = BlocProvider.of<imageCubit>(context);
imageCubit.uploadImage(_image);
Navigator.pop(context);
},
child: Text("Upload"))
],
backgroundColor: Color(0xFF333D81),
);
}
Future<void> _getImage() async {
final PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print("No image selected");
}
});
}
}
After I press the button, it throws the following error:
Error: MissingPluginException(No implementation found for method pickImage on channel plugins.flutter.io/image_picker)
at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5331:11)
at platform_channel.MethodChannel.new._invokeMethod (http://localhost:7357/packages/flutter/src/services/system_channels.dart.lib.js:954:21)
at _invokeMethod.next (<anonymous>)
at http://localhost:7357/dart_sdk.js:39029:33
at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:38886:58)
at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:33872:29)
at handleValueCallback (http://localhost:7357/dart_sdk.js:34432:49)
at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:34470:17)
at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:34312:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:34335:35)
at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:39173:13)
at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:39179:13)
at http://localhost:7357/dart_sdk.js:34686:9
I already tried calling flutter clean, flutter pub get and rerunning my app, but it didn't help.
How can I solve this issue?
Thanks for your help in advance!
Try adding the package image_picker_for_web to your pubspec.yaml file.
...
dependencies:
...
image_picker: ^0.6.7
image_picker_for_web: ^0.1.0
...
...
then modify your _getImage method:
Future<void> _getImage() async {
final PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
if (kIsWeb) { // Check if this is a browser session
_image = Image.network(pickedFile.path);
} else {
_image = Image.file(File(pickedFile.path));
}
} else {
print("No image selected");
}
});
}
I think this is what made it work for me. I was getting the same error message as you.

ZXing is not scanning on Android (Xamarin app)

I am using below code to scan a QR code in my Xamarin. I am currently testing it on Samsung Galaxy (Android) and I am able to view the camera streaming but it is not scanning any QR code.
How can I fix this please to get the result of the QR scanned?
public void Scan()
{
try
{
scanner.Options = new MobileBarcodeScanningOptions()
{
UseFrontCameraIfAvailable = false, //update later to come from settings
PossibleFormats = new List(),
TryHarder = true,
AutoRotate = false,
TryInverted = true,
DelayBetweenContinuousScans = 2000,
};
scanner.VerticalOptions = LayoutOptions.FillAndExpand;
scanner.HorizontalOptions = LayoutOptions.FillAndExpand;
// scanner.IsVisible = false;
scanner.Options.PossibleFormats.Add(BarcodeFormat.QR_CODE);
// scanner.Options.PossibleFormats.Add(BarcodeFormat.DATA_MATRIX);
// scanner.Options.PossibleFormats.Add(BarcodeFormat.EAN_13);
scanner.OnScanResult += (result) => {
// Stop scanning
scanner.IsAnalyzing = false;
scanner.IsScanning = false;
if (scanner.IsScanning)
{
scanner.AutoFocus();
}
// Pop the page and show the result
Device.BeginInvokeOnMainThread(async () => {
if (result != null)
{
await DisplayAlert("Scan Value", result.Text, "OK");
}
});
};
mainGrid.Children.Add(scanner, 0, 1);
}
catch (Exception ex)
{
DisplayAlert("Scan Value", ex.ToString(), "Error");
}
}
Maybe you are using the wrong event handler, or missing an event, also the camera never focuses:
the condition is never true, due to this fragment of code:
scanner.IsScanning = false;
if (scanner.IsScanning)
{
scanner.AutoFocus();
}

Resources