Skip to content

Commit

Permalink
Combine with local restapi
Browse files Browse the repository at this point in the history
Add users and drawer page

Refer to the local restapi source:
  https://github.com/yungwenpeng/nodejs-example
  • Loading branch information
yungwenpeng committed Oct 27, 2022
1 parent a586a22 commit 266f3b7
Show file tree
Hide file tree
Showing 26 changed files with 1,702 additions and 165 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1 +1 @@
API_URL="http://localhost:8080"
API_URL="http://localhost:3000"
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,18 @@ samples, guidance on mobile development, and a full API reference.

Introduction to localizations in Flutter: view [internationalization](https://docs.flutter.dev/development/accessibility-and-localization/internationalization)

## Demo:
## Getting test RESTAPI
You can run "http://localhost:3000" from the [nodejs-example](https://github.com/yungwenpeng/nodejs-example)

## Reference packages
package [dio](https://pub.dev/packages/dio)
package [freezed](https://pub.dev/packages/freezed)
package [jwt_decoder](https://pub.dev/packages/jwt_decoder)
package [flutter_secure_storage](https://pub.dev/packages/flutter_secure_storage)

## With test RESTAPI Demo:
![flutter_with_localapi_example](flutter_with_localapi_example.gif)

## Simple Demo:
![flutter-dashboard-example](flutter_example.gif)

4 changes: 4 additions & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ linter:

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

analyzer:
errors:
invalid_annotation_target: ignore
Binary file added flutter_with_localapi_example.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions lib/controllers/controllers.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export 'dio_base.dart';
export 'user_base.dart';
export 'user_api.dart';
161 changes: 161 additions & 0 deletions lib/controllers/dio_base.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Refer to https://pub.dev/packages/dio

import 'package:dio/dio.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

class DioClientController {
var _dio = Dio();
final _baseUrl = dotenv.get('API_URL', fallback: 'API_URL not found.');

DioClientController() {
_dio = Dio(BaseOptions(
baseUrl: _baseUrl,
//connectTimeout: 5000,
//receiveTimeout: 3000,
));
initializeInterceptors();
}

initializeInterceptors() {
_dio.interceptors.clear();
_dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
//print('send request: URL:${options.baseUrl}${options.path}');
return handler.next(options);
},
onResponse: (response, handler) {
return handler.next(response);
},
onError: (DioError e, handler) {
return handler.next(e);
},
));
}

/*Future<Response> _request(
String path,
String method, {
dynamic data,
Map<String, dynamic>? queryParameters,
CancelToken? cancelToken,
ProgressCallback? onSendProgress,
ProgressCallback? onReceiveProgress,
}) async {
Response response;
try {
response = await _dio.request(path,
data: data,
queryParameters: queryParameters,
options: Options(method: method),
cancelToken: cancelToken,
onSendProgress: onSendProgress,
onReceiveProgress: onReceiveProgress);
} on DioError catch (e) {
print(e.message);
throw Exception(e.message);
}
return response;
}
Future<Response> get(String path) async {
return _request(path, 'get');
}*/

Future<Response> get(
String url, {
Map<String, dynamic>? queryParameters,
Options? options,
CancelToken? cancelToken,
ProgressCallback? onReceiveProgress,
}) async {
try {
return await _dio.get(
url,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken,
onReceiveProgress: onReceiveProgress,
);
} on DioError catch (e) {
print(e.message);
throw Exception(e.message);
}
}

Future<Response<T>> post<T>(
String url, {
data,
Map<String, dynamic>? queryParameters,
Options? options,
CancelToken? cancelToken,
ProgressCallback? onSendProgress,
ProgressCallback? onReceiveProgress,
}) async {
//print('POST url: $url');
//print('POST data : $data');
try {
return await _dio.post(
url,
data: data,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken,
onSendProgress: onSendProgress,
onReceiveProgress: onReceiveProgress,
);
} on DioError catch (e) {
print(e.message);
throw Exception(e.message);
}
}

Future<Response> put(
String url, {
data,
Map<String, dynamic>? queryParameters,
Options? options,
CancelToken? cancelToken,
ProgressCallback? onSendProgress,
ProgressCallback? onReceiveProgress,
}) async {
try {
return await _dio.put(
url,
data: data,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken,
onSendProgress: onSendProgress,
onReceiveProgress: onReceiveProgress,
);
} on DioError catch (e) {
print(e.message);
throw Exception(e.message);
}
}

Future<dynamic> delete(
String url, {
data,
Map<String, dynamic>? queryParameters,
Options? options,
CancelToken? cancelToken,
ProgressCallback? onSendProgress,
ProgressCallback? onReceiveProgress,
}) async {
try {
final Response response = await _dio.delete(
url,
data: data,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken,
);
return response.data;
} on DioError catch (e) {
print(e.message);
throw Exception(e.message);
}
}
}
119 changes: 119 additions & 0 deletions lib/controllers/user_api.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import 'dart:convert';
import 'dart:developer';
import 'package:dio/dio.dart';

import '../models/users.dart';
import 'dio_base.dart';

class UserApiController {
final DioClientController dioClient;

UserApiController({required this.dioClient});

Future<List<Users>> getAllUsers() async {
try {
final Response response = await dioClient.get('/api/users?query=all');
final jsonStr = json.encode(response.data);
final result = usersFromJson(jsonStr);
//print('UserApiController - getAllUsers: $result');
return result;
} on DioError catch (e) {
if (e.response != null) {
print('getAllUsers Dio Error!\nSTATUS:${e.response?.statusCode}');
print('DATA: ${e.response?.data}\nHEADERS: ${e.response?.headers}');
} else {
// Error due to setting up or sending the request
print('getAllUsers Error sending request!');
print(e.message);
}
}
return [];
}

Future<Users?> getUser(String email) async {
try {
final response = await dioClient.get('/api/users?query=all');
final jsonStr = json.encode(response.data);
final result = usersFromJson(jsonStr);
//print('UserApiController - getUser result: $result');
for (var user in result) {
if (user.email == email) {
print('UserApiController - getUser: $user');
return user;
}
}
} on DioError catch (e) {
if (e.response != null) {
print('getUser Dio Error!\nSTATUS: ${e.response?.statusCode}');
print('DATA: ${e.response?.data}\nHEADERS: ${e.response?.headers}');
} else {
// Error due to setting up or sending the request
print('getUser Error sending request!');
print(e.message);
}
}
return null;
}

Future<Users?> createUser(
String name, String email, String password, String role) async {
Users? retrievedUser;
try {
final response = await dioClient.post('/api/users/signup', data: {
"userName": name,
"email": email,
"password": password,
"role": role
});
retrievedUser = Users.fromJson(response.data);
//print('createNewUser retrievedUser: $retrievedUser');
return retrievedUser;
} on DioError catch (e) {
if (e.response != null) {
print('createNewUser Dio Error!\nSTATUS: ${e.response?.statusCode}');
print('DATA: ${e.response?.data}\nHEADERS: ${e.response?.headers}');
} else {
// Error due to setting up or sending the request
print('createNewUser Error sending request!');
print(e.message);
}
}
return null;
}

Future<Users?> updateUser(String oldEmail, String name, String email,
String password, String role) async {
Users? updateUser;
try {
final response = await dioClient.put('/api/users/$oldEmail', data: {
"userName": name,
"email": email,
"password": password,
"role": role
});
updateUser = Users.fromJson(response.data);
print('updateUser updateUser: $updateUser');
return updateUser;
} on DioError catch (e) {
if (e.response != null) {
print('updateUser Dio Error!\nSTATUS: ${e.response?.statusCode}');
print('DATA: ${e.response?.data}\nHEADERS: ${e.response?.headers}');
} else {
// Error due to setting up or sending the request
print('updateUser Error sending request!');
print(e.message);
}
}
return null;
}

Future<void> deleteUser(String email) async {
try {
final response = await dioClient.delete('/api/users/$email');
print('User $email deleted!');
inspect(response);
} catch (e) {
print('Error deleting user: $e');
}
}
}
Loading

0 comments on commit 266f3b7

Please sign in to comment.