Why does flutter app always crash after debugging - laravel

this is the main.dart file if there is anyone can help me. after crashing it stuck on this message :
Launching lib\\main.dart on sdk gphone x86 arm in debug mode...
lib\\main.dart:1
√ Built build\\app\\outputs\\flutter-apk\\app-debug.apk.
like this
import 'package:dio/dio.dart';
class BaseUrl {
static String url = 'https://awad.mohatim.tech/public/api';
static String real = 'https://awad.mohatim.tech/api/';
static String local = 'http://127.0.0.1:8000/api/';
}
Map<String, String> headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
class DioHelper {
static final BaseOptions _options = BaseOptions(
baseUrl: BaseUrl.real,
headers: headers,
validateStatus: (status) {
return status! < 500;
},
);
static final Dio _dio = Dio(_options);
// get login # data = email and password
static Future getLogin({required Map<String, dynamic> data}) async {
try {
Response response = await _dio.post('login', data: data);
return response;
} on DioError catch (e) {
print(e.message);
}
}
// data = name email phone paswword
static Future register({required Map<String, dynamic> data}) async {
try {
Response response = await _dio.post('register', data: data);
return response;
} on DioError catch (e) {
print(e.message);
}
}
// public request
static Future post({required String endpoint, required dynamic data}) async {
Map<String, String> headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
try {
Response response = await _dio.post(endpoint, data: data, options: Options(headers: headers));
return response;
} on DioError catch (e) {
print(e.message);
}
}
// public request
static Future get({required String endpoint}) async {
try {
Response response = await _dio.get(endpoint);
return response;
} on DioError catch (e) {
print(e.message);
}
}
static Future getWithToken({required String endpoint, required String token}) async {
Map<String, String> headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
};
try {
Response response = await _dio.get(endpoint, options: Options(headers: headers));
return response;
} on DioError catch (e) {
print(e.message);
}
}
static Future postWithToken({required String endpoint, required dynamic data, required String token}) async {
Map<String, String> headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
};
try {
Response response = await _dio.post(endpoint, data: data, options: Options(headers: headers));
return response;
} on DioError catch (e) {
print(e.message);
}
}
static Future postImage({required String endpoint, required FormData data, required String token}) async {
Map<String, String> headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
};
try {
Response response = await _dio.post(endpoint, data: data, options: Options(headers: headers));
return response;
} on DioError catch (e) {
print(e.message);
}
}
}
I'm trying to connect the app with Laravel admin panel throw API

Related

Black Screen after deleting the record

I am using Laravel as the Backend API and Flutter for the Client. Category Add and Category Update features are working without any issue. However, when i delete a category, the category gets deleted from the database but returns the user to a black page. I am finding difficult to find the error.
lib\screens\categories.dart
import 'package:flutter/material.dart';
import 'package:demo_app/models/category.dart';
import 'package:demo_app/widgets/category_edit.dart';
import 'package:demo_app/providers/category_provider.dart';
import 'package:provider/provider.dart';
// import '../widgets/category_add.dart';
import 'package:demo_app/widgets/category_add.dart';
// import 'package:http/http.dart' as http;
class Categories extends StatefulWidget {
const Categories({super.key});
#override
State<Categories> createState() => _CategoriesState();
}
class _CategoriesState extends State<Categories> {
#override
Widget build(BuildContext context) {
final provider = Provider.of<CategoryProvider>(context);
List<Category> categories = provider.categories;
return Scaffold(
appBar: AppBar(
title: const Text('Categories'),
),
body: ListView.builder(
itemCount: categories.length,
itemBuilder: (context, index) {
Category category = categories[index];
return ListTile(
title: Text(category.name),
trailing:
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: const Icon(Icons.edit),
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) {
return CategoryEdit(category, provider.updateCategory);
});
},
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () => showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('confirmation'),
content: const Text('Are you sure you want to delete?'),
actions: [
TextButton(
onPressed: () => deleteCategory(provider.deleteCategory, category),
child: const Text('Confirm')
),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel')
),
]
);
}
),
),
],
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (BuildContext context) {
return CategoryAdd(provider.addCategory);
});
},
child: const Icon(Icons.add)
),
);
}
Future deleteCategory(Function callback, Category category) async{
await callback(category);
if (!mounted) return;
Navigator.pop(context);
}
}
lib\providers\category_provider.dart
import 'package:demo_app/models/category.dart';
import 'package:demo_app/providers/auth_provider.dart';
import 'package:demo_app/services/api.dart';
import 'package:flutter/material.dart';
class CategoryProvider extends ChangeNotifier{
List<Category> categories = [];
late ApiService apiService;
late AuthProvider authProvider;
CategoryProvider(this.authProvider){
apiService = ApiService(authProvider.token);
init();
}
Future init() async{
categories = await apiService.fetchCategories();
notifyListeners();
}
Future<void> addCategory(String name) async{
try{
Category addedCategory = await apiService.addCategory(name);
categories.add(addedCategory);
notifyListeners();
} catch(e){
await authProvider.logOut();
// ignore: avoid_print
// print(e);
}
}
Future<void> updateCategory(Category category) async{
try{
Category updatedCategory = await apiService.updateCategory(category);
int index = categories.indexOf(category);
categories[index] = updatedCategory;
notifyListeners();
} catch(e){
await authProvider.logOut();
}
}
Future<void> deleteCategory(Category category) async{
try{
await apiService.deleteCategory(category.id);
categories.remove(category);
notifyListeners();
} catch(e){
await authProvider.logOut();
}
}
}
lib\services\api.dart
// import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:demo_app/models/category.dart';
import 'package:demo_app/models/transaction.dart';
// import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class ApiService{
late String token;
ApiService(this.token);
final String baseUrl = 'http://flutter-api.test/api/';
Future<List<Category>> fetchCategories() async {
http.Response response =
await http.get(Uri.parse('${baseUrl}categories'),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
List categories = jsonDecode(response.body);
return categories.map((category) => Category.fromJson(category)).toList();
}
Future <Category> addCategory(String name) async {
String uri = '${baseUrl}categories';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({'name': name}));
if(response.statusCode != 201){
throw Exception('Error happened on create');
}
return Category.fromJson(jsonDecode(response.body));
}
Future <Category> updateCategory(Category category) async {
// String uri = '${baseUrl}categories/$category.id';
String uri = '${baseUrl}categories/${category.id}';
http.Response response = await http.put(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({'name': category.name}));
if(response.statusCode != 200){
throw Exception('Error happened on update');
}
return Category.fromJson(jsonDecode(response.body));
}
Future<void> deleteCategory(id) async {
String uri = '${baseUrl}categories/$id';
http.Response response = await http.delete(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
if(response.statusCode != 204){
// // ignore: avoid_print
// ignore: avoid_print
print(response.statusCode);
// ignore: avoid_print
print(response.body.toString());
throw Exception('Error happened on delete');
}
}
Future<List<Transaction>> fetchTransactions() async {
http.Response response = await http.get(
Uri.parse('${baseUrl}transactions'),
headers: {
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
List transactions = jsonDecode(response.body);
return transactions.map((transaction) => Transaction.fromJson(transaction)).toList();
}
Future<Transaction> addTransaction(String amount, String category, String description, String date) async {
String uri = '${baseUrl}transactions';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({
'amount': amount,
'category_id': category,
'description': description,
'transaction_date': date
}));
if (response.statusCode != 201) {
throw Exception('Error happened on create');
}
return Transaction.fromJson(jsonDecode(response.body));
}
Future<Transaction> updateTransaction(Transaction transaction) async {
String uri = '${baseUrl}transactions/${transaction.id}';
http.Response response = await http.put(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({
'amount': transaction.amount,
'category_id': transaction.categoryId,
'description': transaction.description,
'transaction_date': transaction.transactionDate
}));
if (response.statusCode != 200) {
throw Exception('Error happened on update');
}
return Transaction.fromJson(jsonDecode(response.body));
}
Future<void> deleteTransaction(id) async {
String uri = '${baseUrl}transactions/$id';
http.Response response = await http.delete(
Uri.parse(uri),
headers: {
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
if (response.statusCode != 204) {
throw Exception('Error happened on delete');
}
}
Future<String> register(String name, String email, String password, String passwordConfirm, String deviceName) async {
// ignore: prefer_interpolation_to_compose_strings
String uri = baseUrl + 'auth/register';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
},
body: jsonEncode({
'name': name,
'email': email,
'password': password,
'password_confirmation': passwordConfirm,
'device_name': deviceName
})
);
if(response.statusCode == 422){
Map<String, dynamic> body = jsonDecode(response.body);
Map<String, dynamic> errors = body['errors'];
String errorMessage = '';
errors.forEach((key, value){
value.forEach((element){
errorMessage += element + '\n';
});
});
throw Exception(errorMessage);
}
// if(response.statusCode == 422){
// throw Exception('Error happened on registration');
// }
return response.body;
}
Future<String> login(String email, String password, String deviceName) async {
// ignore: prefer_interpolation_to_compose_strings
String uri = baseUrl + 'auth/login';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
},
body: jsonEncode({
'email': email,
'password': password,
'device_name': deviceName
})
);
if(response.statusCode == 422){
Map<String, dynamic> body = jsonDecode(response.body);
Map<String, dynamic> errors = body['errors'];
String errorMessage = '';
errors.forEach((key, value){
value.forEach((element){
errorMessage += element + '\n';
});
});
throw Exception(errorMessage);
}
// if(response.statusCode == 422){
// throw Exception('Error happened on registration');
// }
return response.body;
}
}
lib\providers\auth_provider.dart
import 'package:demo_app/services/api.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AuthProvider extends ChangeNotifier{
bool isAuthenticated = false;
late String token;
late ApiService apiService;
AuthProvider() {
init();
}
Future<void> init() async {
token = await getToken();
if (token.isNotEmpty) {
isAuthenticated = true;
}
apiService = ApiService(token);
notifyListeners();
}
Future<void> register(String name, String email, String password, String passwordConfirm, String deviceName) async{
token = await apiService.register(name, email, password, passwordConfirm, deviceName);
isAuthenticated = true;
setToken();
notifyListeners();
}
Future<void> logIn(String email, String password, String deviceName) async{
token = await apiService.login(email, password, deviceName);
isAuthenticated = true;
setToken();
notifyListeners();
}
Future<void> logOut() async{
token = '';
isAuthenticated = false;
setToken();
notifyListeners();
}
Future<void> setToken() async{
final pref = await SharedPreferences.getInstance();
pref.setString('token', token);
}
Future<String> getToken() async {
final pref = await SharedPreferences.getInstance();
final token = pref.getString("token") ?? "";
return token;
}
}
lib\main.dart
import 'package:demo_app/providers/auth_provider.dart';
import 'package:demo_app/providers/transaction_provider.dart';
import 'package:demo_app/screens/home.dart';
import 'package:demo_app/screens/login.dart';
import 'package:demo_app/screens/register.dart';
import 'package:demo_app/screens/categories.dart';
// import 'package:demo_app/screens/transactions.dart';
import 'package:flutter/material.dart';
import 'package:demo_app/providers/category_provider.dart';
import 'package:provider/provider.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget{
const MyApp({super.key});
#override
Widget build(BuildContext context){
return ChangeNotifierProvider(
create: (context) => AuthProvider(),
child: Consumer<AuthProvider>(builder: (context, authProvider, child){
return MultiProvider(
providers: [
ChangeNotifierProvider<CategoryProvider>(
create: (context) => CategoryProvider(authProvider)),
ChangeNotifierProvider<TransactionProvider>(
create: (context) => TransactionProvider(authProvider)),
],
child: MaterialApp(
title:'Welcome to Flutter',
routes: {
'/': (context) {
final authProvider = Provider.of<AuthProvider>(context);
if(authProvider.isAuthenticated){
return const Home();
}else{
return const Login();
}
},
'/login': (context) => const Login(),
'/register': (context) => const Register(),
'/categories': (context) => const Categories(),
}));
}
)
);
}
}
lib\screens\categories.dart
Future deleteCategory(Function callback, Category category, BuildContext context) async{
await callback(category);
if (!mounted) return;
Navigator.pop(context);
}
Solved the issue
I changed the headers in the lib\services\api.dart too
lib\services\api.dart
looks like this
// import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:demo_app/models/category.dart';
import 'package:demo_app/models/transaction.dart';
// import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class ApiService{
late String token;
ApiService(this.token);
final String baseUrl = 'http://flutter-api.test/api/';
Future<List<Category>> fetchCategories() async {
http.Response response =
await http.get(Uri.parse('${baseUrl}categories'),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
List categories = jsonDecode(response.body);
return categories.map((category) => Category.fromJson(category)).toList();
}
Future <Category> addCategory(String name) async {
String uri = '${baseUrl}categories';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({'name': name}));
if(response.statusCode != 201){
throw Exception('Error happened on create');
}
return Category.fromJson(jsonDecode(response.body));
}
Future <Category> updateCategory(Category category) async {
String uri = '${baseUrl}categories/${category.id}';
http.Response response = await http.put(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({'name': category.name}));
if(response.statusCode != 200){
throw Exception('Error happened on update');
}
return Category.fromJson(jsonDecode(response.body));
}
Future<void> deleteCategory(id) async {
String uri = '${baseUrl}categories/$id';
http.Response response = await http.delete(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
if(response.statusCode != 204){
// // ignore: avoid_print
// ignore: avoid_print
print(response.statusCode);
// ignore: avoid_print
print(response.body.toString());
throw Exception('Error happened on delete');
}
}
Future<List<Transaction>> fetchTransactions() async {
http.Response response = await http.get(
Uri.parse('${baseUrl}transactions'),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
List transactions = jsonDecode(response.body);
return transactions.map((transaction) => Transaction.fromJson(transaction)).toList();
}
Future<Transaction> addTransaction(String amount, String category, String description, String date) async {
String uri = '${baseUrl}transactions';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({
'amount': amount,
'category_id': category,
'description': description,
'transaction_date': date
}));
if (response.statusCode != 201) {
throw Exception('Error happened on create');
}
return Transaction.fromJson(jsonDecode(response.body));
}
Future<Transaction> updateTransaction(Transaction transaction) async {
String uri = '${baseUrl}transactions/${transaction.id}';
http.Response response = await http.put(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
body: jsonEncode({
'amount': transaction.amount,
'category_id': transaction.categoryId,
'description': transaction.description,
'transaction_date': transaction.transactionDate
}));
if (response.statusCode != 200) {
throw Exception('Error happened on update');
}
return Transaction.fromJson(jsonDecode(response.body));
}
Future<void> deleteTransaction(id) async {
String uri = '${baseUrl}transactions/$id';
http.Response response = await http.delete(
Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $token'
},
);
if (response.statusCode != 204) {
throw Exception('Error happened on delete');
}
}
Future<String> register(String name, String email, String password, String passwordConfirm, String deviceName) async {
// ignore: prefer_interpolation_to_compose_strings
String uri = baseUrl + 'auth/register';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
},
body: jsonEncode({
'name': name,
'email': email,
'password': password,
'password_confirmation': passwordConfirm,
'device_name': deviceName
})
);
if(response.statusCode == 422){
Map<String, dynamic> body = jsonDecode(response.body);
Map<String, dynamic> errors = body['errors'];
String errorMessage = '';
errors.forEach((key, value){
value.forEach((element){
errorMessage += element + '\n';
});
});
throw Exception(errorMessage);
}
// if(response.statusCode == 422){
// throw Exception('Error happened on registration');
// }
return response.body;
}
Future<String> login(String email, String password, String deviceName) async {
// ignore: prefer_interpolation_to_compose_strings
String uri = baseUrl + 'auth/login';
http.Response response = await http.post(Uri.parse(uri),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
},
body: jsonEncode({
'email': email,
'password': password,
'device_name': deviceName
})
);
if(response.statusCode == 422){
Map<String, dynamic> body = jsonDecode(response.body);
Map<String, dynamic> errors = body['errors'];
String errorMessage = '';
errors.forEach((key, value){
value.forEach((element){
errorMessage += element + '\n';
});
});
throw Exception(errorMessage);
}
// if(response.statusCode == 422){
// throw Exception('Error happened on registration');
// }
return response.body;
}
}

Flutter app gave an error after performing the necessary integration with laravel api, it returned null

I have a signup page having done all the necessary integration my flutter app still not posting
Here I have my signup method
_signup() async {
var data = {
'first': firstNameController.text,
'last': lastNameController.text,
'email': emailController.text,
'phone': phoneController.text,
'age': ageController.dropDownValue!.name,
'gender': genderController.dropDownValue!.name,
'password': passwordController.text,
'confirm': confirmPasswordController.text
};
print(data);
var res = await CallApi().postData(data, 'register');
print(res);
var body = json.decode(res.body);
print(body);
}
Why I have the api authentication here which is well configured
import 'package:http/http.dart' as http;
class CallApi {
final String baseURL = 'https://beereapp.edusmart.ng/api/auth/';
postData(data, apiUrl) async {
var fullUrl = baseURL + apiUrl;
return await http.post(
Uri.parse(fullUrl),
body: jsonEncode(data),
headers: _setHeaders());
}
getData(apiUrl) async {
var fullUrl = Uri.parse(baseURL + apiUrl);
return await http.get(fullUrl, headers: _setHeaders());
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
}
As you can see my terminal below I printed my data out which is showing but next is error.
Help please!
[![My terminal][1]][1]
[1]: https://i.stack.imgur.com/10uMa.jpg

I'm getting "Unauthenticated" message with a valid token in Laravel Passport using Flutter

I built a Web Service using Laravel Passport for authentication, when I register a user, it generates an access token successfully, but when I am trying to retrieve the user info, I get unauthenticated.
The interesting part is that making the social sign up with Postman, the access token generated works, but when I make the sign up with the app, the access token is not valid.
This is my request code on my mobile app:
Future<Map> socialSignIn(UserSocialAuth userSocialAuth) async {
final String _socialPath = '/social_auth';
Future<Map> socialSignInResponse;
try {
socialSignInResponse = postRequest(_socialPath, userSocialAuth.toJson());
} catch (error, stackTrace) {
print("Exception ocurred: $error stackTrace: $stackTrace");
socialSignInResponse = jsonDecode('{"exception": $error, "stackTrace": $stackTrace}');
}
return socialSignInResponse;
}
/// POST Request
Future<Map> postRequest(String serviceName, Map data) async {
Map responseData = {};
FormData formData = FormData.fromMap(data);
_dio.options.connectTimeout = connectTimeout;
_dio.options.receiveTimeout = receiveTimeout;
try {
Response response = await _dio.post(
_endpoint + '$serviceName',
data: formData,
options: Options(
headers: {
'Authorization': await getAccessToken(),
'Accept': 'application/json'
}
)
);
if (response.statusCode == 200) {
responseData = response.data;
}
} catch (e) {
// An error was received
responseData = {
'error': 'No se pudo conectar con el servidor de $_appName',
'exception': e.toString()
};
}
return responseData;
}
And this is the request for the user data using access token:
Future<Map> currentUser(String accessToken) async {
final String _currentUserPath = '/user';
Future<Map> userDataResponse;
try {
userDataResponse = getRequest(_currentUserPath);
} catch (error, stackTrace) {
print("Exception ocurred: $error stackTrace: $stackTrace");
userDataResponse = jsonDecode('{"exception": $error, "stackTrace": $stackTrace}');
}
return userDataResponse;
}
/// GET Request
Future<Map> getRequest(String serviceName) async {
Map responseData = {};
_dio.options.connectTimeout = connectTimeout;
_dio.options.receiveTimeout = receiveTimeout;
try {
Response response = await _dio.get(
_endpoint + '$serviceName',
options: Options(
headers: {
'Authorization': await getAccessToken(),
'Accept': 'application/json'
}
));
if (response.statusCode == 200) {
responseData = response.data;
}
} catch (e) {
// An error was received
responseData = {
'error': 'No se pudo conectar con el servidor de $_appName',
'exception': e.toString()
};
}
return responseData;
}
I do not know why works with postman and not with the app.
I save the access token with SharedPreferences like this:
/// ----------------------------------------------------------
/// Method that returns the token from Shared Preferences
/// ----------------------------------------------------------
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<String> getAccessToken() async {
final SharedPreferences prefs = await _prefs;
String _authorizationToken;
if (prefs.getString(_accessTokenKey) != null) {
_authorizationToken = 'Bearer ' + prefs.getString(_accessTokenKey);
}
return _authorizationToken;
}
/// ----------------------------------------------------------
/// Method that saves the token in Shared Preferences
/// ----------------------------------------------------------
Future<bool> setAccessToken(String token) async {
final SharedPreferences prefs = await _prefs;
return prefs.setString(_accessTokenKey, token);
}

Error during upload image to imgur - inavlid URL

i have some troubles with imgur api. I converted image to base64 code and tried upload it to imgur api. Unfortuatelly I'm receiving an error:
"error": "Invalid URL (data:image/png;base64,iVBORw0KGgoAA..."
Here's my function:
uploadImageToImgur: function (file) {
const url = 'https://api.imgur.com/3/image',
reader = new FileReader();
reader.onloadend = async function () {
let { result } = reader;
try {
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'my client key',
},
body: result
});
const response = await request.json();
console.log(response);
} catch (e) {
throw new Error(e);
}
}
if (file) {
reader.readAsDataURL(file);
}
}
You need to cut this part out.
You are missing some parameters. Also, make sure your headers have the Client-ID key.
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'Client-ID {yourKey}',
},
form: {
"image": result,
"type": "base64"
}
});

How call WebAPi in phonegap?

I am calling Web API by using Datajs and it is working in each browser but when i am calling this by Phonegap then i am getting error
Http Request failed.
function DefaultHandler() {
var oldDefaultHandler = OData.defaultHandler;
OData.defaultHandler = {
accept: oldDefaultHandler.accept,
read: function (response, context) {
var contentType = response.headers["Content-Type"];
if (contentType && contentType.indexOf("text/html") === 0) {
response.data = response.body;
} else {
oldDefaultHandler.read(response, context);
}
},
write: function (request, context) {
oldDefaultHandler.write(request, context);
}
};
}
function GetContact() {
$('#products').html('');
OData.defaultHttpClient.enableJsonpCallback = true;
DefaultHandler();
OData.read(
{
requestUri: "http://192.168.11.46/odata/Contact",
enableJsonpCallback: false,
datatype: "json",
headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Content-Type': 'application/json', 'Accept': 'text/html', "Authorization-Token": "94,214,182,1,98,51,181,18,190,167,152,19,225,97,211,221,145,78,188,26,247,172,226,13,90,113,105,2,226,15,137,12,190,22,95,226,215,9,111,95,162,33,36,220,238,197,99,169,158,140,170,61,3,186,190,97,244,173,125,212,3,135,172,111,235,229,133,101,234,188,104,188,127,10,188,221,72,120,48,25,184,56,215,80,87,83,117,30,57,241,133,80,137,220,185,220,230,0,20,122,181,0,106,69,234,27,106,212,187,77,77,27,39,159,31,253,140,105,43,167,210,238,35,71,44,251,180,199" },
method: "GET"
},
success,
error
);
}
success = function (data) {
alert('success Odata');
};
error = function (err) {
alert('error Odata');
};
Is there any setting that i need to set in Eclipse or in emulator.

Resources