flutter visibility error and initState problem - laravel

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);
});
});

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: 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).

Convert Uint8List image data to ImageGallerySaver saveFile String

how can I convert the Uint8List imagedata of the Screenshot Package to save it with the ImageGallerySaver package saveFile command, which needs a string?
TextButton(
onPressed: () {
_imageFile = null;
screenshotController
.capture()
.then((Uint8List image) async {
//print("Capture Done");
setState(() {
_imageFile = image;
});
final result = await ImageGallerySaver.saveFile();
print("File Saved to Gallery");
}).catchError((onError) {
print(onError);
});
I found a solution:
TextButton(
onPressed: () {
_imageFile = null;
screenshotController
.capture()
.then((Uint8List image) async {
//print("Capture Done");
String dir =
(await getApplicationDocumentsDirectory()).path;
File file = File("$dir/" +
DateTime.now().millisecondsSinceEpoch.toString() +
".png");
await file.writeAsBytes(image);
setState(() {
_imageFile = image;
});
final result =
await ImageGallerySaver.saveFile(file.path);
print("File Saved to Gallery");
}).catchError((onError) {
print(onError);
});
},
child: Icon(Icons.change_history),
), // Thi

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

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;
});
}
}

Nuxt SSR return loaded image dimensions to server

I'm trying to preview a profile photo on an existing img element my problem is that the new image dimension become undefined outside of the img load function.
How can i pass these dimensions to the server so that i can properly resize the img element?
I've tried using Vuex Store as well to pass the dimensions but with the same undefined results.
I also have a function that listens for resize and after a user changes the window the img is resized properly, however i'm trying to do this without the event trigger. Even when i try to manually trigger the resize event with jQuery it does not resize. I'm under the impression that somehow the dimension of the new img source are not being set properly until a resize even refreshes the dimensions?
<b-img id="profilePhoto" v-bind="profile" :src="this.photo" class="profilePhoto" #change="handleResize()"></b-img>
export default {
data() {
return {
errors:{},
profile: {},
fileDimensions: {},
photo: '',
form: this.$vform({
id: '',
name: '',
email: '',
password: '',
role: '',
bio: '',
photo: ''
})
}
}
}
getPhoto(e) {
let file = e.target.files[0];
if (typeof file !== 'undefined'){
let reader = new FileReader()
let limit = 1024 * 1024 * 2
if (file.size > limit) {
return false;
}
reader.onloadend = (file) => {
this.form.photo = reader.result
this.photo = this.form.photo
}
reader.readAsDataURL(file)
$("<img/>",{
load : function(){
// will return dimensions fine if i use alert here
this.fileDimensions = { width:this.width, height:this.height} ;
},
src : window.URL.createObjectURL(file)
});
// becomes undefined outside of the load functions
var aw = this.fileDimensions.width
var ah = this.fileDimensions.height
var ph = $('.profile').height()
var pw = $('.profile').width()
console.log(this.fileDimensions.width)
if (ah>aw){
this.profile = { width: ph, height: 'auto'}
} else if (aw>ah) {
this.profile = { width: 'auto', height: ph}
} else {
this.profile = { width: ph+10, height: pw+10}
}
}
}
I expect to get the dimensions so i can determine how to set the width and height properties for the img element with its new src however the dimension become undefined.
I figured it out through another post. I had to create a promise. async await in image loading
getDimensions(src){
return new Promise((resolve,reject) => {
let img = new Image()
img.onload = () => resolve({ height: img.height, width: img.width })
img.onerror = reject
img.src = src
})
},
getPhoto(e) {
let file = e.target.files[0];
if (typeof file !== 'undefined'){
let reader = new FileReader()
let limit = 1024 * 1024 * 2
if (file.size > limit) {
return false;
}
reader.onloadend = (file) => {
this.form.photo = reader.result
this.photo = this.form.photo
}
reader.readAsDataURL(file)
this.getDimensions(URL.createObjectURL(file))
.then((dimensions) => {
if (process.client){
var ah = $('.profile').height()
var aw = $('.profile').width()
var ph = dimensions.height
var pw = dimensions.width
if (ph>pw){
this.profile = { width: ah+10, height: 'auto'}
} else if (pw>ph) {
this.profile = { width: 'auto', height: ah+10}
} else {
this.profile = { width: ah+10, height: aw+10}
}
}
})
}
}

Resources