How to set flutter POST method using DIO? - flutter

This is my code below, i'm stuck please help. How to set flutter POST method using DIO?
Map<String, dynamic> toJson() {
return {
'id': id,
"name": name,
"telNumber": telNumber,
"email": email,
"age": age
};
}
String postToJson(Post data){
final dyn = data.toJson();
return json.encode(dyn);
}
Future<http.Response> createPost(Post post) async {
final response = await http.post(
"$baseUrl/users",
headers: {
"content-type": "application"
},
body: postToJson(post));
return response;
}
This method works in http

BaseOptions options = new BaseOptions(
baseUrl: $baseUrl,
connectTimeout: 10000,
receiveTimeout: 10000,);
final dioClient = Dio(options);
try{
final response = await dioClient.post("/users", data: FormData.fromMap(
postToJson(post))
),);
return response;
} catch (e) {
throw (e);
}
Put this code inside the function

you can create a new function and call this from anywhere:
Future<Null> SendPost() async {
Response response;
BaseOptions options = new BaseOptions(
baseUrl: "https://your.url",
connectTimeout: 6000,
receiveTimeout: 3000,
);
Dio dio = new Dio(options);
FormData formData = new FormData.fromMap({
"post_data1": value,
"post_data2": value,
});
try {
response=await dio.post("/page.php", data: formData);
return response;
} catch (e) {
print('Error: $e');
}
}

Related

non-local notification using workManager flutter

i tried to send notification to another device when the app is terminated using workManager
it does not work, however the same function works if i use it without workManager
here is the code
in the main
await Workmanager().initialize(callBAckDispatcher, isInDebugMode: true);
callBackDispathcer
callBAckDispatcher() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
Workmanager().executeTask((taskName, inputData) async {
if (taskName == "t") {
int id = 7
await sFunction(id, await returnUserName());
}
return Future.value(true);
});
}
sFunction
sFunction(int id, String sender) async {
List<Map> response =
await SQLdb().readData('''SELECT * FROM `timer_chat` WHERE id = $id
''');
String reciever = response[0]['reciever'];
String message = response[0]['message'];
try {
String currentToken = await auth.getusertoken(reciever);
auth.sendnotify("my app",
"your message has been sent: " + message, "1", currentToken);
} catch (e) {
print("notification did not send: " + e.toString());
}
}
finally sendnotify
sendnotify(String title, String body, String id, String token) async {
try {
await http.post(
Uri.parse("https://fcm.googleapis.com/fcm/send"),
headers: <String, String>{
'content-type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': body.toString(),
'title': title.toString()
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': "FLUTTER_NOTIFICATION_CLICK",
'id': id.toString(),
"name": "me",
"lastname": "wolf"
},
"to": token
},
),
);
} catch (e) {
print("something went wrong in notiiiii" + e.toString());
}
}
i'm sending notifications using firebase cloud messaging API. it worked fine inside the app but in workManager it does not. any idea why?
thank you

Infobip SMS bulk messages API with flutter/dart

My post request doesn't work
I've tried running this but i end up with :
{"requestError":{"serviceException":{"messageId":"UNAUTHORIZED","text":"Invalid logindetails"}}}
This is my code :
data() async {
final client = HttpClient();
final request = await client .postUrl(Uri.parse("https://....api.infobip.com/sms/2/text/advanced")); request.headers.set(HttpHeaders.contentTypeHeader, "{'Authorization':'App ...KEY','Content-Type': 'application/json','Accept': 'application/json'}");
request.write({ '"messages": [{"from": "sms","destinations": [{"to": "..."}],"text": "ABC"}]' });
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(contents);
});
}
I just figured out an answer for this POST request in flutter
makePostRequest(int number) async {
final uri = Uri.parse('https://....api.infobip.com/sms/2/text/advanced');
final headers = {
'Authorization':
'App API-KEY',
'Content-Type': 'application/json'
};
Map<String, dynamic> body = {
"messages": [
{
"from": "SenderID",
"destinations": [
{"to": number}
],
"text": "TEST!"
}
]
};
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
Response response = await post(
uri,
headers: headers,
body: jsonBody,
encoding: encoding,
);
int statusCode = response.statusCode;
String responseBody = response.body;
print(responseBody);
}

DioError [DioErrorType.other]: Converting object to an encodable object failed: _LinkedHashSet len:1 Flutter

I want to print data from the api but i am getting this error below:
DioError [DioErrorType.response]: Http status error [500]
Check the screenshot below from postman, It is working well.
Below is my code, I need help. I get error when I call this function below:
Future<void> signInData([data]) async {
final prefs = await SharedPreferences.getInstance();
final String token = prefs.getString('token') ?? "";
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
{
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
}
},
options: Options(headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
}));
print(response.data);
print(response.statusCode);
if (response.statusCode == 401) {
// call your refresh token api here and save it in shared preference
await getToken();
signInData(data);
}
} catch (e) {
print(e);
}
}
Hey remove extra { from data inside post method like below -
Future<void> signInData([data]) async {
final prefs = await SharedPreferences.getInstance();
final String token = prefs.getString('token') ?? "";
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
},
options: Options(headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
}));
print(response.data.toString());
print(response.statusCode);
if (response.statusCode == 401) {
// call your refresh token api here and save it in shared preference
await getToken();
signInData(data);
}
} catch (e) {
print(e);
}
}

how to connect API with flutter Dio

I'm trying to connect the below API into my flutter code. but I'm getting below error. how to solve this. appreciate your help on this.
I/flutter (15198): null I/flutter (15198):
{"success":false,"code":210,"status":"Unauthorized","msg":"You are not
authorized to visit this route"}
Map<String, String> loginUserData = {
'email': '',
'password': '',
'id': '',
'userName': '',
'token': '',
'userStatus': '',
'wallet_address': '',
};
#override
void initState() {
_Unlockchallenge();
//dynamic.initState();
asyncMethod();
}
void asyncMethod() async {
await _Unlockchallenge();
}
Future _Unlockchallenge() async {
var response;
print(response);
try {
response = await Dio().get(BASE_API + "challenge/getChallengeByUserAndType/calories",
options: Options(headers: {
'Authorization':loginUserData["token"], //HEADERS
}
));
print(response);
} catch (e) {
print(e);
//throw Exception('Unable to get data');
}
}
the header need to be like this
'Authorization': 'Bearer ${loginUserData["token"]}'

Flutter post request parse

I have a POST request:
static String url = 'https://checkout.test.paycom.com/api';
static Map<String, String> headers = {
'Host': 'checkout.test.paycom.com',
'X-Auth': '1234',
'Cache-Control': 'no-cache'
};
Future<Map<String, dynamic>> createCard() async {
try {
Map<String, dynamic> body = {
"id": '123',
"method": "receipts.create",
"params": {
"amount": '2500',
"account": {"order_id": '106'}
}
}
final response = await http.post(url, body: body, headers: headers);
print(response.body);
} catch (e) {
print(e.toString());
}
return null;
}
and give an error
type '_InternalLinkedHashMap<String, Object>' is not a subtype of type 'String' in type cast
What I am doing wrong?
your body needs to be as string, best case for you could be convert your body as JSON String as below:
final response = await http.post(url, body: jsonEncode(body), headers: headers);