I want to display a list of image in carousel slider ,data are coming from api ..How to display images coming from list.
here is my api
Future<List<ImageModel>> _getImageList() async {
final url =
Uri.parse('http://45.34.15.25/API/api/v1/MerchandiseImage/GetMerchandiseImage?OrganizationId=1');
var response = await http.get(
url,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'tenant-code': 'flatworld',
},
);
// print(response.body);
if (response.body.isNotEmpty) {
final result = jsonDecode(response.body);
print(result);
Iterable imageList = result["result"];
print(imageList.length);
return imageList.map((record) => ImageModel.fromJson(record)).toList();
} else {
throw Exception("Failed to load data!");
}
}
carousel_slider: ^4.1.1
By using this plug in, you can complete.
Related
I am getting this error
flutter: response body:{"Message":"The request entity's media type 'text/plain' is not supported for this resource."}
which i am getting in post whenever i am changing the body type to text instead of json. How can i solve this.
here are the postman screenshots of both successful request and field request are given below
Here is the post method
Future<String> sendRequest() async {
var jsonArray = json.encode(body);
algo.Encrypted encrypted = Algorithm.encrypt(algorithmKey, jsonArray);
var encryptedBosy = jsonEncode({'body': encrypted.base64});
var response = await https.post(
Uri.parse("$baseUrl/$paymentMethod"),
headers: {
"Key": key,
"secretKey": secretKey,
},
body: encryptedBosy,
);
return response.body;
}
Add the content type header to the request.
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
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(),));
}
});
}
}
i have been working on flutter project which accepts name and phone number of users but when i save it it shows response 500 but from post man its working fine.
but from flutter here is the code
void RegisterUsers(String names, String phone) async{
String urlInser = "https://hmmmiii.com/api/addUser";
Map<String, String> headers = {
'Content-Type': 'application/json',
//'Accept': 'application/json',
};
final msg = jsonEncode({"Name":"$names","PhoneNumber":"$phone"});
var response = await http.post(urlInser,
headers: headers,
body: msg);
print(response.statusCode);
if (response.statusCode == 200) {
print('User Registered');
} else {
print('Unsuccessful');
}
where names and phone are textController values thanks.
in postman, you are sending the request as form-data, but in your code, you are sending it as a simple JSON.
you have to use MultipartRequest instead.
final url = 'your url';
final request = http.MultipartRequest('POST', Uri.parse(url))
..fields['Name'] = 'some name'
..fields['PhoneNumber'] = 'some phonenumber';
final response = await request.send();
final responseBody = await response.stream.bytesToString();
print('RESPONSE BODY: $responseBody');
I'm trying to fetch a json file from a https link however, no matter what link a give the result does not change!?
I validated all the json files. in case they had an error.
the responseData stays the same, and even when I force the data to change by instead returning responseData returning a json manually written; it changes right back to the old json data that just doesnt change when I return responseData back.
And the responseData that I requested to be be posted on the console gives the wrong information
The url given is correct.
but the output doesnt correspond to the data when I fill the link in the internetbrowser.
constructor(props){
super(props);
this.state = {
connected: false,
}
this.init = this.init.bind(this);
this.getJson = this.getJson.bind(this);
this.updateVisited = this.updateVisited.bind(this);
}
init = async ({json})=>{
if(json==null){
await AsyncStorage.setItem('database', "");
alert('error occured');
} else {
await AsyncStorage.setItem('database', JSON.stringify(json));
this.setState({
connected: true
});
}
}
getJson = async ()=>{
var url = await AsyncStorage.getItem("database_url");
console.log(url);
return fetch(url,
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => {
this.updateVisited(url);
console.log(responseData);
return responseData;
})
.catch(error => {
alert('Could not connect!');
return null;
})
}
connect = async ({url})=>{
await AsyncStorage.setItem("database_url", url);
this.getJson().then(json => this.init({json}));
}
"a_json": [{"name": "greg"}]
"test": [{"name": "sheldon"}]
"temp": [{"name": "bob"}]
when the url points to the json test it gives bob expecting sheldon
when the url points to the json temp it gives bob expecting bob
when the url points to the json a_json it gives bob expecting greg
when returning a json without trying to fetch it from the internet at the place of responseData; it gives the expecting value
If you need more information, feel free to ask.
Thank you for your time reading my question.
The problem was the Cache-Control.
I added 'Cache-Control': 'no-cache' to the header of the fetch, which fixed the problem!
This was pointed out by #Pritish Vaidya in the comments
I am facing the issue of json added being added to the url after calling the service to add the data.
below is my file
first.ts
CreateNew(): void {
this.router.navigate(['/detail', 0]);
}
detail.ts
Submit() {
let templateId;
this.route.params.subscribe(
(param: any) => {
templateId = +param['templateid']; });
if (templateId === 0) {
this.jobservice.addJob(this.job).subscribe(error => this.errorMessage = <any>error);
}
this.router.navigate(['/template']);
}
service.ts
addJob(job: Job): Observable <Job> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(job);
return this.http.post('http://sample/api/Product/AddProduct', JSON.stringify(job), options).map(this.extractData).catch(this.handleError);
}
I am not able to find the issue why it is adding the json data to the url.
When you use the RequestOption, you dont use the method post, get, put or delete. But you use "request". Here is a sample request that works:
post<RQ, RS>(url: string, request: RQ, responseType: RS, withToken: boolean): Promise<RS> {
let postReq: Request = this.createAuthorizationHeader<RQ>(url, request, RequestMethod.Post, withToken);
return this.http.request(postReq).toPromise()
.then(res => {
return this.processingData<RS>(res, responseType);
})
.catch(this.handleError);
}
Then here you add your header to the request:
/**
* This function updates the token in the header
*/
createAuthorizationHeader<RQ>(url: string, requestData: RQ, method: RequestMethod, withToken: boolean) {
let headers = new Headers();
let options = new RequestOptions({
method: method,
url: url
});
/**
* Include token when boolean is passed
*/
if (withToken) {
headers.append('token', token);
options.headers = headers;
}
/**
* create bosy for post and put
*/
if (method === RequestMethod.Post || method === RequestMethod.Put) {
// do something
}
let request = new Request(options);
return request;
}
This should work, remember to use "http.request.." when you use request options
import { Http, Request, Response, Headers, RequestMethod, RequestOptions } from '#angular/http';
...
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers = headers,
body: job
});
let request = new Request(options);
console.log(options);
return this.http.request(options).map(this.extractData).catch(this.handleError);
The issue was that while refresh of page it was showing 404 error.
In app.module.ts
Add imports: import { HashLocationStrategy, LocationStrategy } from '#angular/common';
And in NgMoudle provider, add: {provide: LocationStrategy, useClass: HashLocationStrategy}
which fixed the issue.
This should be working out fine. I have this working on my environment using angular 2.1.0.
import { Http, Request, Response, Headers, RequestMethod, RequestOptions } from '#angular/http';
...
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
method: RequestMethod.Post,
url: 'localhost:51293/template',
headers = headers,
body: job
});
let request = new Request(options);
console.log(options);
return this.http.request(options).map(this.extractData).catch(this.handleError);