uploading An Image to Database using MultiPartFile in Flutter - flutter

I want to upload an image that I have already retrieved from the database(product table) to the cart table.
The issue is, I can't use the .path with the MultipartFile("file", image.path);
I am getting an error if I try using .path with my image variable. I've also tried several methods but none is working... I'll attach my codes below
The image is already stored in a map(revievedMap) which I receivr from the previous screen so I'm not using an imagePicker, the product image I'm trying to access is already stored in the database.
request.fields['image'] = "http://10.0.2.2:/shopice/assets/${args.product.image}";
request.fields['image'] = "http://localhost:/shopice/assets/${args.product.image}";
I tried the code above, obviously didn't work.
var pic = await http.MultipartFile.fromPath("image", args.product.image!);
//request.files.add(pic);
I also tried this, but I need to set the path on the second argument, but args.product.image.path(), is returning this error
[the getter 'path' isn't defined for the type 'String'. (Documentation) Try importing the library that defines 'path', correcting the name to the name of an existing getter, or defining a getter or field named 'path'.]
here is the code:
//args.receivedMap: is my buyer detials
//args.product: is the product i'm trying to add to cart, which //contains the image
args.seller: is the seller details
child: FlatButton(
onPressed: ()async {
if(!args.receivedMap.isEmpty){
final uri = Uri.parse("http://10.0.2.2:/shopice/api/buyer/addToCart");
var request = http.MultipartRequest('POST', uri);
request.fields['buyer_id'] =args.receivedMap['id'];
request.fields['seller_id'] = args.seller.id.toString();
request.fields['seller_name'] = args.seller.name!;
request.fields['buyer_name'] = args.receivedMap['name'];
request.fields['price'] = args.product.pricePerKg!;
request.fields['product_name'] = args.product.name!;
//request.fields['image'] = "http://10.0.2.2:/shopice/assets/${args.product.image}";
//var pic = await http.MultipartFile.fromPath("image", "http://localhost:/shopice/assets/${args.product.image}");
//File file = "http://10.0.2.2:/shopice/assets/${args.product.image}" as File;
//var pic = await http.MultipartFile.fromString("image", args.product.image!);
//request.files.add(pic);
var bytes = (await rootBundle.load('http://localhost/shopice/assets/${args.product.image}')).buffer.asUint8List();
var mpFile = http.MultipartFile.fromBytes('img', bytes);
request.files.add(mpFile);
var response = await request.send();
print(args.product.image);
if (response.statusCode == 200) {
showModalBottomSheet(context: context, builder: (context){
return Wrap(children: [ListTile(leading: Icon(Icons.done_outline), title: Text('Product Added TO Cart'),)],);
});
}
else if (response.statusCode == 500) {
showModalBottomSheet(context: context, builder: (context){
return Wrap(children: [ListTile(leading: Icon(Icons.done_outline), title: Text('Server Error '),)],);
});
}
else {
showModalBottomSheet(context: context, builder: (context){
return Wrap(children: [ListTile(leading: Icon(Icons.done_outline), title: Text('ERROR WHILE PERFORMING OPPERATION\n CONTACT SUPPORT'),)],);
});
}
}
else if(args.receivedMap.isEmpty){
var snackbar = SnackBar(
content: Text('Login To Add Product To Cart!',
style: TextStyle(fontSize: 16.0)),
backgroundColor:
const Color(0xff4A777A),
padding: EdgeInsets.only(left: 50.0),
);
ScaffoldMessenger.of(context)
.showSnackBar(snackbar);
}
},
child: Text(
'Add to Cart',
style: GoogleFonts.poppins(
color: Color(0xff4A777A)),
)),

i simply add the image from the backend and forget about doing it with flutter, i moved the image with php and did some trial and error which later worked

Related

How to make HTTP GET request in flutter/dart

I am trying to make this GET request in my app but I am not sure how to go about it as I'm fairly new to flutter/dart.
I have successfully made a POST request to log in and now I am trying to make this GET request to display the messages in this message board in my app. That can come later as I am trying to complete the GET request first.
Preferably the GET request should be in a method which I can use in a button; each will be in messageBoard_Page.dart
This is the request URL that I am trying to reach.
and this is the Request Header
for reference this is the response that I am getting from my Login POST method
{
"RESPONSE":{
"login_request_result":{
"user_must_change_password":"0"
},
"BASEL_RESPONSE":{
"UserDate":"0",
"UserTime":"0",
"UserName":"Administrator",
"module_config_1":"0",
"module_config_2":"0",
"ErrEntity":{
"MessageID":"0",
"last_req_id":"50029",
"table_id":"0",
"key_id_list":"536871",
"operation_id":"0"
},
"is_csv":"0",
"VersionName":"DYMA # 6.1.24.0, ORG # 2017.3.22.15.0.41, GRC # 2017.3.22.15.0.55, LDC # 2017.3.22.15.1.8, DYMA_XML # 2017.3.22.15.0.30, NAS # 2017.3.22.15.1.22 - Config: 0 - Node: OPRISK_DATACOLLECTOR",
"ExpiryDate":"31/01/2030",
"count_key":"0",
"id_Us":"1",
"is_popup":"0",
"tot_messages":"0",
"my_messages":"0",
"product":"0"
},
"RESPONSE_HEADER":{
"SessionID":"VtVQIdERO-206868772kpwAXF0001",
"NomeRichiesta":"LOGIN_REQUEST",
"ltimeStart":"22262791",
"ltimeStop":"22262813",
"ldate_null":"19900101",
"product":"1",
"server_name":"OPRISK_DATACOLLECTOR",
"cell_context_id":"537945",
"operation_key":"1000000",
"operation_sub_num":"-1"
}
}
}
and this is my Login POST Method in login_Page.dart
void sendLogin() async {
var map = <String, dynamic>{
"UserName": _usernameController.text,
"Password": _passwordController.text,
};
var res = await http.post(
Uri.parse("http://192.168.1.8:8080/HongLeong/LOGIN_REQUEST.do"),
body: map,
);
final data = jsonDecode(res.body);
final String userSessionID = (data as Map)['RESPONSE']['RESPONSE_HEADER']['SessionID'];
print(res.statusCode);
print(res.body);
await WriteCache.setString(key: "cache", value: userSessionID);
if ((data as Map)['RESPONSE']['login_request_result'] == null) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Center(child: Text('Invalid Username/Password')),
actions: <Widget>[
Center(
child: TextButton(
onPressed: () {
_usernameController.clear();
_passwordController.clear();
Navigator.of(ctx).pop();
},
child: const Text('Ok'),
),
),
],
),
);
} else {
Navigator.push(context,
MaterialPageRoute(builder: (context) => const DashboardPage()));
}
}
please ignore the messiness as Im trying to achieve the GET method as of now.
Any help is appreciated. Thank You.
ps. if the images are too small, I am not sure how else to show the request URL and header, sorry.
To make a get request its very much similar to the post you created. Just remove the body and change the request type
var res = await http.get(
Uri.parse("The url for getting the respose through get method here")
);
Rest everything stays the same.

Not able to display the value of a variable defined out of a widget

i'm new to dart and i'm trying to display the file name inside the Text widget!
I first took out the file's name inside the onPressed function, but later on couldn't access it in order to display it, can anyone help me out with this issue? thank in advance.
Here is my code:
body: Column(
children: [
ElevatedButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
final file = result.files.first;
/* print(file.extension);
print(file.name); */
final FileName = file.name;
final newFile = await saveFilePermanently(file);
print('Old: ${file.path}');
print('New: ${newFile.path}');
},
child: const Text('Name: ')),
],
),
You need to create a variable to store the file name outside your onPressed method and use setState() to update your variable value.
String fileName = '';
...
body: Column(
children: [
ElevatedButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
final file = result.files.first;
/* print(file.extension);
print(file.name); */
final FileName = file.name;
final newFile = await saveFilePermanently(file);
print('Old: ${file.path}');
print('New: ${newFile.path}');
// add this setState to update your variable value
setState(() {
fileName = newFile.path;
});
},
child: const Text('Name: $fileName')), // show your value here
],
),

Get Database from firestore and using within RefreshIndicator in Flutter

Hello everyone, I am getting data from firestore . In this case ı am trying to add in RefreshIndicator() to onRefresh(); when ı am using just a data without query , ı dont see any mistake ,it work clearly like that
tumGonderiler() async {
QuerySnapshot myQuerySnapshot = await akisRef.get();
setState(() {
this.tEdilenGonderiler = myQuerySnapshot.docs.map((e) => e.data()).toList();
});
}
but when ı am trying to query in my collection with where parameter , onRefresh() doesent work in my page , the code that does not work is as follows
tumGonderiler() async {
QuerySnapshot myQuerySnapshot = await akisRef.where("ownerID", whereIn: takipEdilenKullanicilar.map((e) => e.id).toList()).get();
setState(() {
this.tEdilenGonderiler = myQuerySnapshot.docs.map((e) => e.data()).toList();
});
}
I've changed my code a little bit untill now it's working right now you can follow from below
tumGonderiler() async {
QuerySnapshot snapshot1 = await takipEdilenRef.doc(anlikKullanici!.id).collection("takipEdilenler").get();
List<tEdilen> kullaniciress = snapshot1.docs.map((doc) => tEdilen.fromDocument(doc)).toList();
setState(() {
this.takipEdilenKullanicilar = kullaniciress;
});
QuerySnapshot myQuerySnapshot = await akisRef.where("ownerID", whereIn: takipEdilenKullanicilar.map((e) => e.id).toList()).get();
List<Gonderiler> kullanicires = myQuerySnapshot.docs.map((e) => Gonderiler.fromDocument(e)).toList();
setState(() {
this.tEdilenGonderiler = kullanicires;
});
}
return Scaffold(
backgroundColor: Colors.white,
appBar: baslik(context, strBaslik: "Kartlar", geriButonuYokSay: true),
body: RefreshIndicator(
color: Colors.black,
child: ListView(
children: tEdilenGonderiler,
),
onRefresh: () {
return tumGonderiler();
}),
);

Flutter/Dart - Convert image(base64) show error in circle avatar

Convert the image get in to :
final prefs = await SharedPreferences.getInstance();
var image = ((prefs.getString('photo')));
var send = {'name': usu, 'email': email, 'image': photo};
In widget:
Widget _buildDrawer(BuildContext context) { return FutureBuilder<Map>(
future: getFutureDates(), // function where you call your api
builder: (BuildContext context, AsyncSnapshot<Map> snapshot) {
if(!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
} else {
Uint8List profile = base64.decode(snapshot.data['image']); new UserAccountsDrawerHeader(
accountName: new Text((json.encode(snapshot.data['name']).toString().replaceAll('"', ''))),
accountEmail: new Text((json.encode(snapshot.data['email']).toString().replaceAll('"', ''))),
currentAccountPicture: new CircleAvatar(
backgroundImage: MemoryImage((profile)),
),
), } }
The Name and email is ok, but Photo give me a error:
Invalid character (at charact
er 5)
data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD...
Reason:
base64 string contains data:image/png;base64, cause error
data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD
Solution:
remove string data:image/png;base64, , you can use substring(22) and only keep
/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD...
code snippet
void main() {
String base64str = '''data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD''';
String newString = base64str.substring(22);
print(newString);
}
output
/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD

Flutter error while showing profile picture google play games

Using the play_games extension, I'm having trouble returning the user's profile image.
Use the method below to login and set the state with the return of the user's data.
Image provider: NetworkImage ("content: //com.google.android.gms.games.background/images/f56551ac/42", scale: 1.0)
// Google Play Games stance
final GameServices gameservices = GameServices();
Account profile;
ui.Image profileimage;
void _login() async {
final res = await gameservices.login();
final resimage = await res.hiResImage;
setState(() {
profile = res;
profileimage = resimage;
});
print(profileimage);
}
In the widget I'm in the form of NetworkImage, but it's still not rendering on the screen.
this error: The argument type 'Image' can't be assigned to the parameter type 'String'.
Container(
width: 128,
height: 128,
padding: EdgeInsets.all(8),
child: CircleAvatar(
backgroundImage: NetworkImage(this.profileimage != null ? this.profileimage : 'https://api.adorable.io/avatars/128/')
),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle
),
),
[ RESOLVED!!! ]
Change my code and play_games returns type vars.
Lets go:
Future<Uint8List> get hiResImage async =>
await _fetchToMemory(await _channel.invokeMethod('getHiResImage'));
Future<Uint8List> get iconImage async =>
await _fetchToMemory(await _channel.invokeMethod('getIconImage'));
}
Future<Uint8List> _fetchToMemory(Map<dynamic, dynamic> result) {
Uint8List bytes = result['bytes'];
if (bytes == null) {
print('was null, mate');
return Future.value(null);
}
// Completer<Image> completer = new Completer();
// decodeImageFromList(bytes, (image) => completer.complete(image));
return Future.value(bytes);
}
And my code, only this change:
Uint8List profileimage;
Flutter is yelling at you because you gave it a URL with protocol content://, when it expects http:// or https:// for a NetworkImage widget. See documentation at: https://flutter.dev/docs/cookbook/images/network-image
This happen because google provide encoded image. In android we can use ImageManager for that as google suggest.
In flutter there are mechanism for getting Future<Image> from hiresImageUri. Check here.
Use Something like below,
profile.hiResImage.then((Image result){
//here you can get image in result
});