Parse json in background using Dart's 'compute' - json

I am trying to use Json using the 'compute' method as I investigate ways to speed up my application. https://api.flutter.dev/flutter/foundation/compute.html.
No mention of an install for a package and use cases that I see do not mention any particular imports. https://dev.to/fallenstedt/compute-with-flutter-3p6o, https://github.com/flutter/flutter/issues/16265, Flutter- compute method
Error message:
Compiler message:
lib/account_control.dart:34:26: Error: Method not found: 'compute'.
parsedJson = await compute(jsonDecode, response.body);
Where I call compute
if (response.statusCode == 200) {
parsedJson = await compute(jsonDecode, response.body);
Globals.data = parsedJson;
print("Succesfully set Globals.data");
return true;
}
Class implementation
class AccountControl {
static dynamic getAccDetails() async {
var token = Globals.token;
Globals.tokenDecode = Globals.parseJwt(Globals.token);
Globals.accountId = Globals.tokenDecode["accountId"].toString();
Globals.appUserId = Globals.tokenDecode["appUserId"].toString();
Globals.partitionId = 0;
var baseUrl = Globals.baseUrl; //platform server
var accountId = Globals.accountId;
var host = Globals.host;
var accDetailsUri =
Uri.encodeFull(baseUrl + "t/rest/cp/v1.0/account/" + accountId);
print(accDetailsUri);
Map<String, String> headers = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + token,
'Cache-Control': 'no-cache',
'Host': host
};
var response = await http.get(accDetailsUri, headers: headers);
var parsedJson;
if (response.statusCode == 200) {
parsedJson = await compute(jsonDecode, response.body);
Globals.data = parsedJson;
print("Succesfully set Globals.data");
return true;
}
}
}
Any feedback is appreciated

You need to import foundation.
import 'package:flutter/foundation.dart';

Related

Submission part of code works, but notification not appearing on slack channel I want it to run to

Here is my code
function notifyTeamMembersOfNewRequest(event) {
const response = event.values
console.log(`response values: ${response}`)
let payload = {
text: response,
channel: 'C04AZ4GT2UU'
}
requestSlack('POST', `chat.postMessage`, payload)
}
function requestSlack(method, endpoint, params) {
const base_url = "https://slack.com/api/"
const headers = {
'Authorization': "Bearer " + 'YOUR_SLACK_API_KEY',
'Content-Type' : 'application/json'
}
const options = {
headers: headers,
method: method
}
let request_url
if (method == 'POST') {
request_url = base_url + endpoint
options.payload = JSON.stringify(params)
} else {
request_url = base_url + endpoint + params
}
const response = UrlFetchApp.fetch(request_url, options).getContentText();
const json = JSON.parse(response)
return {
response_code: json.ok,
response_data: json
}
}
Basically I want it to send a new response on a form to a slack channel with the mentioned ID - however while on the executions tab it gives me the desired response; it doesn't send it to the slack channel. Can someone please help?
I have used quite a few Google searches however, no luck.

Flutter sending post request returning http error 500

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

Post form data to server flutter

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

Angular 6 - get csv response from httpClient

Can any one please give an example of fetching application/octet-stream response from angular 6 httpClient. I am using the below code and it doesn't work ( I get unknown error - 401 response) -
import { saveAs } from 'file-saver';
getJobOutput() {
this.workflowService.fetchOutput(this.jobId,this.outputId).subscribe((response : any) => { // download file
var blob = new Blob([response.blob()], {type: 'application/octet-stream'});
var filename = 'file.csv';
saveAs(blob, filename);
});
}
Service is as below -
fetchOutput(jobId : string, outputId) {
var jobOutputURL = "myEnpoint";
var params = this.createHttpAuthorization(jobOutputURL,"GET");
params["format"] = "csv";
const options = {
headers: new HttpHeaders( { 'Content-Type': 'application/octet-stream',
'Accept' : 'application/octet-stream',
'Access-Control-Allow-Origin' : '*'}
)};
var endpoint = `${jobOutputURL}?oauth_consumer_key=${params["oauth_consumer_key"]}&oauth_signature_method=${params["oauth_signature_method"]}&oauth_nonce=${params["oauth_nonce"]}&oauth_timestamp=${params["oauth_timestamp"]}&oauth_version=1.0&format=${params["format"]}&oauth_signature=${params["oauth_signature"]}`;
return this.httpClient.get(endpoint, {...options, responseType: 'blob'});
}
To fetch an application/octet-stream, you have to set arraybuffer as the response type in the Angular HttpHeaders.
This is the service method:
fetchOutput(): Observable<ArrayBuffer> {
let headers = new HttpHeaders();
const options: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
} = {
responseType: 'arraybuffer'
};
return this.httpClient
.get('https://your-service-url.com/api/v1/your-resource', options)
.pipe(
map((file: ArrayBuffer) => {
return file;
})
);
}
This is the call to the service method and to the saveAs function:
this.yourService
.fetchOutput()
.subscribe((data: any) => {
const blob = new Blob([data], { type: 'application/octet-stream' });
const fileName = 'Your File Name.csv';
saveAs(blob, fileName);
})
As other users are suggestion: 401 Unauthorized is usually a client side error due to missing credentials.

Creating flutter Json Login form with user Basic authentication

Have been stuck for quite a while on this step. can someone show me how to send a request such that upon pressing the "login" button a new instance of a user with Basic authentication is created. i would love to understand how to know how the headers are arranged to access the url database
void Login() {
final form = formKey.currentState;
if (form.validate()) {
form.save();
makePost();
}
}
second part my json methond
Future<Post> makePost() async {
String Username = "denisPos";
String Password = "moV4b90WqpHfghghsg";
final response = await http.post('http://.60.4546.109:4520/postRequest',
headers: {HttpHeaders.authorizationHeader: '$Password:$Username:$url'});
final responseJson = json.decode(response.body);
return Post.fromJson(responseJson);
}
class Post {
final String phone;
final String password;
final String body;
Post({this.phone, this.password, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
phone: json['phone'],
password: json['password'],
body: json['body'],
);
}
}
If you are talking about Basic authentication you can have something like the following code:
Future<Post> makePost() async {
String username = "denisPos";
String password = "moV4b90WqpHfghghsg";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Accept": "application/json",
"Authorization": "Basic $credentials"
};
var url = ...
var requestBody = ....
http.Response response = await http.post(url, body: requestBody, headers: headers);
var responseJson = json.decode(response.body);
return Post.fromJson(responseJson);
}
If you are sending a GET request you can omit the requestBody altogether.
http.Response response = await http.get(url, headers: headers);
Future<http.Response> post() async {
var url = 'http://xxxxxxxxxxxxx;
String password = "xxxxxxxxxxxxxxxx;
String username = "
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var requestBody = jsonEncode({ 'phone': phone, 'pass': pass});
http.Response response = await http.post(
url, body: requestBody, headers: headers);
var responseJson = json.decode(response.body);
print(Utf8Codec().decode(response.bodyBytes));
print("Body: " + responseJson);
}