how to handle null safety during api call flutter? - flutter

am trying to do an API call where am getting an error to hangle null safety variable must be assigned.
here is my code
Future<LoginResponseModel> loginCustomer(
String username, String password) async {
LoginResponseModel model;
try {
var response = await Dio().post(Config.tokenURL,
data: {
"username": username,
"password": password,
},
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
}));
if (response.statusCode == 200) {
model = LoginResponseModel.fromJson(response.data);
}
} on DioError catch (e) {
print(e.message);
}
return model;
}
exception am getting
The non-nullable local variable 'model' must be assigned before it can
be used. Try giving it an initializer expression, or ensure that it's
assigned on every execution path.dart
(not_assigned_potentially_non_nullable_local_variable)
is there any solution to handle this
tried "?" it's not working.
Screenshot

Future<LoginResponseModel?> loginCustomer(
String username, String password) async {
LoginResponseModel? model;
try {
var response = await Dio().post(Config.tokenURL,
data: {
"username": username,
"password": password,
},
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
}));
if (response.statusCode == 200) {
model = LoginResponseModel.fromJson(response.data);
}
} on DioError catch (e) {
print(e.message);
}
return model;
}

Related

The method '[]' was called on null Flutter

I try to make some unit tests on a login funtion in flutter and I have an error that I can't fix.
This is the test:
test('Register (success)', () async {
var auth = AuthService();
var result = await auth.login("test", "123456");
var json = jsonDecode(result.toString());
expect(json['success'], true);
});
This is the function called by the test:
login(name, password) async {
if (name.toString().isEmpty || password.toString().isEmpty) {
return "Error: empty field";
}
return await dio.post('https://itsmilife.herokuapp.com/authenticate',
data: {"name": name, "password": password},
options: Options(contentType: Headers.formUrlEncodedContentType))
}
This is the function that sent the informations:
authenticate: function(req, res) {
User.findOne({
name: req.body.name
}, function (err, user) {
if (err) throw err
if (!user) {
res.status(403).send({success: false, msg: 'Authentication Failed, User not found'})
} else {
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
var token = jwt.encode(user, config.secret)
res.json({success: true, token: token, user: user})
}
else {
return res.status(403).send({success: false, msg: 'Authentication failed wrong password'})
}
})
}
})
},
I have the error when I launch the test:
NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("success")
dart:core Object.noSuchMethod
test\widget_test.dart 24:16 main.<fn>
I don't understand how to fix the probleme.
Try something like this:
Future<bool> login(name, password) async {
if (name.toString().isEmpty || password.toString().isEmpty) {
return false;
}
var responseFromServer = await dio.post(
'https://itsmilife.herokuapp.com/authenticate',
data: {"name": name, "password": password},
options: Options(contentType: Headers.formUrlEncodedContentType));
if (responseFromServer == null || responseFromServer.statusCode != 200) {
return false;
}
return true;
}
Also, make your test like:
test('Register (success)', () async {
var auth = AuthService();
var result = await auth.login("test", "123456");
expect(result, true);
});

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

capacitor community/http handle errors

I often use Axios to perform requests in my applications, however due to incompatibility with iphone, I had to use the capacitor-community/http library, however the try catch blocks are always returning success, even if there was an error in the request. How can I handle errors using this library?
try {
await Requester.auth.public.login(formData);
this.$store.dispatch('login', user);
this.$root.$emit('showToast', {
text: 'Seja bem vindo!',
color: 'success',
});
this.$router.push({ name: 'Cotacao' });
} catch (err) {
this.$root.$emit('showToast', {
text: err.response?.data ?? err.toString(),
color: 'error',
});
} finally {
this.loading.submitForm = false;
}
},
My request
const login = async (formData: AuthLoginFormData): Promise<User> => {
const res: HttpResponse = await Http.post({
url: `${BASE_URL}public/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data: formData,
webFetchExtra: {
credentials: 'include',
},
});
return res.data;
};
Install Latest https://github.com/capacitor-community/http plugin
use function
public async login(formData: AuthLoginFormData){
let options = {
url: `${BASE_URL}public/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data: formData,
webFetchExtra: {
credentials: 'include',
}
};
let response: HttpResponse = await Http.request(options);
if (response.status === 200) {
return Promise.resolve(res);
}
return Promise.reject(response.data);
}

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

How to set flutter POST method using DIO?

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