I picked an image from my gallery, then use this image as in my http body parameter , I believe it sending the image in string format thats why its showing this error.How can I display this image in my App ?
I tried to implement with Multipart but didn't came up with any solution, so I stick to this base64 format
void filePicker() async {
final File? selectedImage =
await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
fileContent = image!.readAsBytesSync();
fileContentBase64 = base64.encode(fileContent);
print(fileContentBase64.substring(0, 100));
});
}
Then in my API function use this image with other parameters
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var response = await http.post(
Uri.parse(
"http://medbo.digitalicon.in/json/SaveCustomTestBooking"),
body: ({
'VisitDate': _selectedDate,
'EncUserId': EncUserId,
'UserFile': fileContentBase64 , // here
'Description': testTextController.text
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DieticianAfterDateSelectPage(
rresponse:
DieticianEncBookingIdModel.fromJson(jsonResponse),
)));
} else {
// ScaffoldMessenger.of(context)
// .showSnackBar(SnackBar(content: Text("Somthing went wrong")));
throw Exception("Faild to fetch");
}
}
}
Related
I'm having a problem in flutter...
I'm trying to access my database and I get this error:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Connection refused and changed IP addresses to my IP with 10.0.2.2:8000/api and with 127.0.0.1:8000/api.
Enter to give phpmyadmin to authorize the entry of IP.
with using Flutter laravel Php.
auth_services
class AuthServices {
static Future<http.Response> register(
String name, String email, String password) async {
Map data = {
"name": name,
"email": email,
"password": password,
};
var body = json.encode(data);
var url = Uri.parse(baseURL + '/auth/register');
http.Response response = await http.post(
url,
headers: headers,
body: body,
);
print(response.body);
return response;
}
register_screen
createAccountPressed() async {
bool emailValid = RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(_email);
if (emailValid) {
http.Response response =
await AuthServices.register(_name, _email, _password);
Map responseMap = jsonDecode(response.body);
if (response.statusCode == 200) {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => const HomeScreen(),
));
} else {
errorSnackBar(context, responseMap.values.first[0]);
}
} else {
errorSnackBar(context, 'email not valid');
}
}
globals.dart
import 'package:flutter/material.dart';
const String baseURL = "http://192.168.100.4:8000/api/"; //emulator localhost
const Map<String, String> headers = {"Content-Type": "application/json"};
errorSnackBar(BuildContext context, String text) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text(text),
duration: const Duration(seconds: 1),
));
}
I Took a variable in my State File? image;
Then Accesing image from my device
void filePicker() async {
final File? selectedImage =await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
});
}
Then tyring to pass the image file along with other http body parameters. If I didn't pass the image file, then the API didn't show any error. But I need to pass the image file to get the correct result.
As I Explicitly throw Exception, so its throwing exception like Faild to fetch and message in ScaffoldMessenger --> Somthing went wrong
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var postUri = Uri.parse("http://medbo.digitalicon.in/api/medboapi/SaveCustomTestBooking");
var request = http.MultipartRequest('POST', postUri);
request.fields['VisitDate'] = _selectedDate;
request.fields['EncUserId'] = EncUserId;
request.files.add(new http.MultipartFile.fromBytes('image',await File.fromUri(Uri.parse(image!.path)).readAsBytes(),contentType: new MediaType('image', 'jpeg')));
request.send().then((response) {
if (response.statusCode == 200) {
print("Uploaded!");
Navigator.push(context,MaterialPageRoute(builder: (context) => DieticianAfterDateSelectPage(rresponse:DieticianEncBookingIdModel.fromJson(jsonResponse),)));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Somthing went wrong")));
throw Exception("Faild to fetch");
}
});
}
}
You should use MultiPart post method. Take a look at this.
You can pass image file simply in this way:
//header
var headers = {
'content-type': 'multipart/form-data',
'Accept': 'application/json',
};
//setup request
var request = http.MultipartRequest(
"POST", Uri.parse("your api url"));
//add files to reqest body
request.files.add(await http.MultipartFile.fromPath(
'your feild name',
pickedFile.path,
));
//add header
request.headers.addAll(headers);
//send request and return response
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
}
Finally managed to slove it using Multipart.. Here is full API function code of mine
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var response = http.MultipartRequest('POST',Uri.parse("http://myApiTestBooking"));
response.fields['VisitDate'] = _selectedDate;
response.fields['EncUserId'] = EncUserId;
response.fields['Description'] = testTextController.text;
response.files.add(new http.MultipartFile.fromBytes(
"UserFile", File(image!.path).readAsBytesSync(),//UserFile is my JSON key,use your own and "image" is the pic im getting from my gallary
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));
response.send().then((response) async {
if (response.statusCode == 200){
isApiCallProcess = false;
final respBody = await response.stream.bytesToString();// this is how we print body for Multipart request
jsonResponse = json.decode(respBody.toString());
print(respBody);
print("Uploaded!");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Booked"),
backgroundColor: Color(0xFF00b3a4),
));
// Navigator.push(context,new MaterialPageRoute( builder: (context) =>new MyTestReqDetailsPage(),));
Navigator.push(context,new MaterialPageRoute( builder: (context) =>new Home2(),));
}
});
}
}
Basically I want to collect my API data in an array AND add new data to my array every time I'm calling my API, then use map function to construct my dynamic row...I hope you understood my problem.
My code, try to construct dynamic row by collecting data in an Array
Future<void> GetTestFee() async {
var jsonResponse;
if (encTestId.isNotEmpty) {
var response = await http.post(
Uri.parse("http://getrbi.in/api/agtyi/GetTestFee"),
body: ({
'EncPartnerId': encLabId,
'EncTestId': encTestId,
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
getTestFeeObj=GetTestFeeMap.fromJson(jsonResponse);
} else {
throw Exception("Faild to fetch");
}
} else {
throw Exception("Faild to fetch");
}
//throw Exception("Faild to fetch");
return GetTestFee();
}
JSON resresponse
{
"EncPartnerId": "LEuT1eIlpLiuiiyAAkZme3wpQ==",
"EncTestId": "U4exk+vfMGrn7cjNUa/kji==",
"Fee": "100",
"DiscountedFee": "80",
"BookingFee": "50"
}
You can add your model to list:
List<GetTestFeeMap> reponseModel =[]
And after getting you response add it into list
var response = await http.post(
Uri.parse("http://ytyttiiiuiu.in/api/medboapi/GetTestFee"),
body: ({
'EncPartnerId': encLabId, // can use for test run "LEuT1eIlpLEMAAkZme3wpQ==",
'EncTestId': encTestId, // "U4exk+vfMGrn7cjNUa/PBw=="
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
getTestFeeObj=GetTestFeeMap.fromJson(jsonResponse);
reponseModel.add(getTestFeeObj)
I hope I undrestand right.
I believe response.statusCode == 200 from my Api because its printing Uploaded! How can I store my API response in a variable (Lets say "jsonResponse") so that I can pass it to my new MaterialPage DieticianAfterDateSelectPage?
The Error:
The method '[]' was called on null.
Receiver: null
Tried calling: []("Status")
The relevant error-causing widget was
MaterialApp
lib\main.dart:19
//
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var postUri = Uri.parse("http://mkklklklklktBooking");
var request = http.MultipartRequest('POST',postUri);
request.fields['VisitDate'] = '_selectedDate';
request.fields['EncUserId'] = 'EncUserId';
request.files.add(new http.MultipartFile.fromBytes(
"UserFile", File(image!.path).readAsBytesSync(),
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));
request.send().then((response){
if (response.statusCode == 200) {
print("Uploaded!"); //From here.............
Navigator.push(context, MaterialPageRoute(builder: (context) => DieticianAfterDateSelectPage(rresponse:DieticianEncBookingIdModel.fromJson(jsonResponse),)));
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Somthing went wrong")));
throw Exception("Faild to fetch");
}
}
);}
My variable image contain my gallery image after method call.
final ImagePicker _picker = ImagePicker();
File? image;
var fileContent;
var fileContentBase64;
Function to get image from gallery
void filePicker() async {
final File? selectedImage =
await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
fileContent = image!.readAsBytesSync();
fileContentBase64 = base64.encode(fileContent);
});
}
It's not very clear how to help. I can see that you are passing a value to DieticianAfterDateSelectPage, and your error message. But you are asking how to store the value in a variable!
What you probably need is to understand the error message. You are getting it because you are calling the [] operator on null. You need to check how that's happening, and check the line number 19 in your main.dart as in the error message.
This is how I print my Multipart request body
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var response = http.MultipartRequest('POST',Uri.parse("http://myApiTestBooking"));
response.fields['VisitDate'] = _selectedDate;
response.fields['EncUserId'] = EncUserId;
response.fields['Description'] = testTextController.text;
response.files.add(new http.MultipartFile.fromBytes(
"UserFile", File(image!.path).readAsBytesSync(),
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));
response.send().then((response) async {
if (response.statusCode == 200){
isApiCallProcess = false;
final respBody = await response.stream.bytesToString();// this is how we print body for Multipart request
jsonResponse = json.decode(respBody.toString());
print(respBody);
print("Uploaded!");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Booked"),
backgroundColor: Color(0xFF00b3a4),
));
// Navigator.push(context,new MaterialPageRoute( builder: (context) =>new MyTestReqDetailsPage(),));
Navigator.push(context,new MaterialPageRoute( builder: (context) =>new Home2(),));
}
});
}
}
I have been having a lot of trouble sending a post request to a server. It expects a form data type.
This is the error I get after my input.
`image: [The image must be an image.]}}
Most of my data are strings except for an int and a file Image which is selected from gallery by user.
This is my code:
dart code
if(_image!=null){
setState(() {
_isLoading = true;
});
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host +
AuthUtils.updateSessionRequest;
Map<String, String> data = {"_method": "PATCH",
"first_name": widget.first_name,
"last_name": widget.last_name,
"phone": widget.phone,
"industry":widget.industry,
"country": widget.country,
"state": widget.state,
"fav_quote": widget.fav_quote,
"bio_interest": widget.bio_text,
"terms": "1",
"company": widget.company,
"position": widget.job_position,
"linked_in":widget.linkedin_profile,
"institution": widget.institution,
"degree": widget.degree,
"preference[0]": widget.industry};
String authToken = sharedPreferences.getString("token");
try {
final response = await http.post(
uri,
body: data,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + authToken,
},
);
final responseJson = json.decode(response.body);
print(responseJson.toString());
if (response.statusCode == 200 || response.statusCode == 201) {
//upload image to server after success response
uploadImage(_image);
NetworkUtils.showToast("Profile successfully update!");
});
} else{
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
return responseJson;
} catch (exception) {
print(exception.toString());
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
}
uploadImage(File image) async{
var request = http.MultipartRequest(
"POST",
Uri.parse(NetworkUtils.host +
AuthUtils.endPointUpdateProfile));
request.files.add(await http.MultipartFile.fromPath(
'image',
image.path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
}
}
You need to pass your image like this
request.files.add(await http.MultipartFile.fromPath(
'image',
_image,
));
Here an example how to pass File and String using http
var request = http.MultipartRequest(
"POST",
Uri.parse("http://....."));
request.fields['first_name'] = widget.first_name;
request.fields['last_name'] = widget.last_name;
.....
request.files.add(await http.MultipartFile.fromPath(
'image',
path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
From the above only, with a little modification
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void executePostMethod(String title) async {
var request = http.MultipartRequest("POST", Uri.parse("https://localhost:44377/API/GetStateList"));
request.fields['CountryID'] = "1";
// .....
//request.files.add(await http.MultipartFile.fromPath('image',path,)
//);
// send request to upload image
await request.send().then((response) async {
//print(response);
response.stream.transform(utf8.decoder).listen((value) async {
print(value);
// print("ResponseVal: $value");
if (response.statusCode == 200) {
var imgUploadData = json.decode(value);
print(imgUploadData);
} else {
throw Exception("Faild to Load!");
}
});
}).catchError((e) {
print(e);
});
}