Commit e05a1210 authored by Ilham Maulana's avatar Ilham Maulana 💻

fix: common bug

parent c38d625c
class User { class User {
int id; int id;
int accountId;
String username; String username;
String email; String email;
String? firstName; String? firstName;
String? lastName; String? lastName;
bool isStaff; bool isStaff;
User(this.id, this.accountId, this.username, this.email, this.firstName, User(this.id, this.username, this.email, this.firstName, this.lastName,
this.lastName, this.isStaff); this.isStaff);
factory User.fromJson(Map<String, dynamic> data) { factory User.fromJson(Map<String, dynamic> data) {
return User( return User(
data['id'] as int, data['id'] as int,
data['account_id'] as int,
data['username'] as String, data['username'] as String,
data['email'] as String, data['email'] as String,
data['first_name'] as String?, data['first_name'] as String?,
...@@ -36,7 +34,6 @@ class User { ...@@ -36,7 +34,6 @@ class User {
final User initialUser = User( final User initialUser = User(
1, 1,
2,
"test_user", "test_user",
"test@email.com", "test@email.com",
"Test", "Test",
......
...@@ -10,7 +10,9 @@ import 'package:library_app/src/models/user.dart'; ...@@ -10,7 +10,9 @@ import 'package:library_app/src/models/user.dart';
class AuthProvider with ChangeNotifier { class AuthProvider with ChangeNotifier {
final storage = const FlutterSecureStorage(); final storage = const FlutterSecureStorage();
String baseUrl = 'http://localhost:8000/api/v1'; String baseUrl = 'http://localhost:8000/api/v1';
String? message;
User? user; User? user;
bool isAuthenticated = false; bool isAuthenticated = false;
...@@ -57,7 +59,7 @@ class AuthProvider with ChangeNotifier { ...@@ -57,7 +59,7 @@ class AuthProvider with ChangeNotifier {
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
); );
if (response.statusCode == 200) { if (response.statusCode == 201) {
final data = jsonDecode(response.body); final data = jsonDecode(response.body);
String token = Token.fromJson(data)!.key; String token = Token.fromJson(data)!.key;
await storeAccessToken(token); await storeAccessToken(token);
...@@ -132,12 +134,12 @@ class AuthProvider with ChangeNotifier { ...@@ -132,12 +134,12 @@ class AuthProvider with ChangeNotifier {
"password": password, "password": password,
}; };
final response = await http.post( final response = await http.post(
Uri.parse('$baseUrl/members/auth/register'), Uri.parse('$baseUrl/auth/register'),
body: jsonEncode(body), body: jsonEncode(body),
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
); );
if (response.statusCode == 200) { if (response.statusCode == 201) {
final data = jsonDecode(response.body); final data = jsonDecode(response.body);
String token = Token.fromJson(data)!.key; String token = Token.fromJson(data)!.key;
storeAccessToken(token); storeAccessToken(token);
...@@ -169,15 +171,17 @@ class AuthProvider with ChangeNotifier { ...@@ -169,15 +171,17 @@ class AuthProvider with ChangeNotifier {
Uri.parse('$baseUrl/user'), Uri.parse('$baseUrl/user'),
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Authorization': 'Bearer $token' 'Authorization': 'Bearer $token',
}, },
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = jsonDecode(response.body); final data = jsonDecode(response.body);
user = User.fromJson(data); user = User.fromJson(data);
message = null;
} else { } else {
debugPrint('Error fetching user details: ${response.statusCode}'); debugPrint(
'Error fetching user details: ${response.statusCode} ${response.body}');
} }
setLoading(false); setLoading(false);
...@@ -189,6 +193,7 @@ class AuthProvider with ChangeNotifier { ...@@ -189,6 +193,7 @@ class AuthProvider with ChangeNotifier {
} }
Future<void> updateUserDetail( Future<void> updateUserDetail(
BuildContext context,
int id, int id,
String username, String username,
String email, String email,
...@@ -201,14 +206,15 @@ class AuthProvider with ChangeNotifier { ...@@ -201,14 +206,15 @@ class AuthProvider with ChangeNotifier {
if (token != null) { if (token != null) {
try { try {
final body = jsonEncode({ final data = {
"username": username, "username": username,
"email": email, "email": email,
"first_name": firstName, "first_name": firstName,
"last_name": lastName, "last_name": lastName,
}); };
final body = jsonEncode(data);
final response = await http.put( final response = await http.put(
Uri.parse('$baseUrl/user/$id/'), Uri.parse('$baseUrl/user/update'),
body: body, body: body,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...@@ -217,9 +223,14 @@ class AuthProvider with ChangeNotifier { ...@@ -217,9 +223,14 @@ class AuthProvider with ChangeNotifier {
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = jsonDecode(response.body); await getUserDetail();
user = User.fromJson(data); message = null;
if (context.mounted) {
context.pop();
}
} else { } else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint( debugPrint(
'Error update user details: ${response.statusCode}, ${response.body}'); 'Error update user details: ${response.statusCode}, ${response.body}');
} }
...@@ -234,19 +245,20 @@ class AuthProvider with ChangeNotifier { ...@@ -234,19 +245,20 @@ class AuthProvider with ChangeNotifier {
Future<void> changePassword( Future<void> changePassword(
BuildContext context, BuildContext context,
int accountId,
String oldPassword, String oldPassword,
String newPassword, String newPassword1,
String newPassword2,
) async { ) async {
final token = await getAccessToken(); final token = await getAccessToken();
try { try {
setLoading(true); setLoading(true);
final response = await http.post( final response = await http.put(
Uri.parse('$baseUrl/members/$accountId/change-password'), Uri.parse('$baseUrl/auth/change-password'),
body: jsonEncode({ body: jsonEncode({
"old_password": oldPassword, "old_password": oldPassword,
"new_password": newPassword, "new_password1": newPassword1,
"new_password2": newPassword2,
}), }),
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...@@ -255,11 +267,14 @@ class AuthProvider with ChangeNotifier { ...@@ -255,11 +267,14 @@ class AuthProvider with ChangeNotifier {
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
message = null;
if (context.mounted) { if (context.mounted) {
context.go("/"); context.go("/");
} }
changePasswordSucced = true; changePasswordSucced = true;
} else { } else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint( debugPrint(
'Change password failed: ${response.statusCode}, ${response.body}'); 'Change password failed: ${response.statusCode}, ${response.body}');
} }
...@@ -271,18 +286,24 @@ class AuthProvider with ChangeNotifier { ...@@ -271,18 +286,24 @@ class AuthProvider with ChangeNotifier {
} }
} }
Future<void> resetPassword(String email) async { Future<void> resetPassword(BuildContext context, String email) async {
try { try {
setLoading(true); setLoading(true);
final response = await http.post( final response = await http.post(
Uri.parse('$baseUrl/reset-password/request-token'), Uri.parse('$baseUrl/auth/reset-password'),
body: jsonEncode({"email": email}), body: jsonEncode({"email": email}),
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
message = null;
resetPasswordTokenSended = true; resetPasswordTokenSended = true;
if (context.mounted) {
context.go("/confirm-reset-password");
}
} else { } else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint( debugPrint(
'Error reset user password: ${response.statusCode}, ${response.body}'); 'Error reset user password: ${response.statusCode}, ${response.body}');
} }
...@@ -295,7 +316,11 @@ class AuthProvider with ChangeNotifier { ...@@ -295,7 +316,11 @@ class AuthProvider with ChangeNotifier {
} }
Future<void> confirmResetPassword( Future<void> confirmResetPassword(
int pin, String password1, String password2) async { BuildContext context,
int pin,
String password1,
String password2,
) async {
setLoading(true); setLoading(true);
final body = jsonEncode({ final body = jsonEncode({
"pin": pin, "pin": pin,
...@@ -305,14 +330,20 @@ class AuthProvider with ChangeNotifier { ...@@ -305,14 +330,20 @@ class AuthProvider with ChangeNotifier {
try { try {
final response = await http.post( final response = await http.post(
Uri.parse('$baseUrl/reset-password/confirm'), Uri.parse('$baseUrl/auth/reset-password-confirm'),
body: body, body: body,
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
message = null;
resetPasswordSucced = true; resetPasswordSucced = true;
if (context.mounted) {
context.go("/");
}
} else { } else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint( debugPrint(
'Error confirm reset user password: ${response.statusCode}, ${response.body}'); 'Error confirm reset user password: ${response.statusCode}, ${response.body}');
} }
...@@ -328,7 +359,7 @@ class AuthProvider with ChangeNotifier { ...@@ -328,7 +359,7 @@ class AuthProvider with ChangeNotifier {
setLoading(true); setLoading(true);
final token = await getAccessToken(); final token = await getAccessToken();
String url = '$baseUrl/members/${user?.accountId}/loans/'; String url = '$baseUrl/user/loans';
if (filterByUpcoming) { if (filterByUpcoming) {
url += '?near_outstanding=True'; url += '?near_outstanding=True';
} else if (filterByOverdued) { } else if (filterByOverdued) {
...@@ -347,9 +378,12 @@ class AuthProvider with ChangeNotifier { ...@@ -347,9 +378,12 @@ class AuthProvider with ChangeNotifier {
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
message = null;
final data = jsonDecode(response.body); final data = jsonDecode(response.body);
memberLoans = data["results"]; memberLoans = data;
} else { } else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint( debugPrint(
"Failed to get member loan. ${response.statusCode}: ${response.body}"); "Failed to get member loan. ${response.statusCode}: ${response.body}");
} }
...@@ -377,6 +411,7 @@ class AuthProvider with ChangeNotifier { ...@@ -377,6 +411,7 @@ class AuthProvider with ChangeNotifier {
Future<void> createMemberLoan(int memberId, int bookId, int loanDay) async { Future<void> createMemberLoan(int memberId, int bookId, int loanDay) async {
final token = await getAccessToken(); final token = await getAccessToken();
String url = '$baseUrl/user/loans';
final now = DateTime.now(); final now = DateTime.now();
final dueDate = now.add(Duration(days: loanDay)); final dueDate = now.add(Duration(days: loanDay));
...@@ -390,7 +425,7 @@ class AuthProvider with ChangeNotifier { ...@@ -390,7 +425,7 @@ class AuthProvider with ChangeNotifier {
try { try {
setLoading(true); setLoading(true);
final response = await http.post( final response = await http.post(
Uri.parse('$baseUrl/members/$memberId/loans/'), Uri.parse(url),
body: jsonEncode(body), body: jsonEncode(body),
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...@@ -399,18 +434,20 @@ class AuthProvider with ChangeNotifier { ...@@ -399,18 +434,20 @@ class AuthProvider with ChangeNotifier {
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = jsonDecode(response.body); message = null;
memberLoans = data["results"]; await getMemberLoan();
} else { } else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint( debugPrint(
"Failed to create member loan. ${response.statusCode}: ${response.body}"); "Failed to add member loan. ${response.statusCode}: ${response.body}");
} }
loanBookSuccess = true; loanBookSuccess = true;
setLoading(false); setLoading(false);
notifyListeners(); notifyListeners();
} catch (error) { } catch (error) {
debugPrint("Failed to create member loan. $error"); debugPrint("Failed to add member loan. $error");
} }
} }
......
...@@ -23,7 +23,7 @@ class BookProvider with ChangeNotifier { ...@@ -23,7 +23,7 @@ class BookProvider with ChangeNotifier {
setLoading(true); setLoading(true);
String url = '$baseUrl/books'; String url = '$baseUrl/books';
if (filterByCategory != null) { if (filterByCategory != null) {
url += '?category__name=$filterByCategory'; url += '?category=$filterByCategory';
} else if (searchKeyword != null) { } else if (searchKeyword != null) {
url += "?search=$searchKeyword"; url += "?search=$searchKeyword";
} }
...@@ -35,7 +35,7 @@ class BookProvider with ChangeNotifier { ...@@ -35,7 +35,7 @@ class BookProvider with ChangeNotifier {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = jsonDecode(response.body); final data = jsonDecode(response.body);
books = data["results"]; books = data;
} else { } else {
final code = response.statusCode; final code = response.statusCode;
debugPrint("Error: Fetch books failed, $code"); debugPrint("Error: Fetch books failed, $code");
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:library_app/src/models/category.dart'; import 'package:library_app/src/models/category.dart';
import 'package:library_app/src/providers/auth_provider.dart'; import 'package:library_app/src/providers/auth_provider.dart';
import 'package:library_app/src/providers/book_provider.dart'; import 'package:library_app/src/providers/book_provider.dart';
...@@ -73,31 +74,53 @@ class _MemberListScreen extends State<MemberListScreen> { ...@@ -73,31 +74,53 @@ class _MemberListScreen extends State<MemberListScreen> {
const BookList(), const BookList(),
// Loans // Loans
LoanList( LoanList(
memberId: authProvider.user?.accountId ?? 0, memberId: authProvider.user?.id ?? 0,
), ),
// Profile // Profile
const Profile(), const Profile(),
][navProvider.currentPageIndex], ][navProvider.currentPageIndex],
drawer: Drawer( drawer: Drawer(
child: ListView( child: Column(
padding: EdgeInsets.zero, children: [
children: List.generate( Padding(
category != null ? category.length : 0, padding: const EdgeInsets.symmetric(
(index) { horizontal: 10.0, vertical: 20.0),
if (category != null) { child: Row(
return ListTile( mainAxisAlignment: MainAxisAlignment.start,
title: Text(category.elementAt(index).name), children: [
onTap: () { ElevatedButton(
bookProvider.filterBookByCategory( child: const Row(
category!.elementAt(index).name); children: [Icon(Icons.arrow_back), Text("Back")],
bookProvider.getBooks(); ),
Navigator.pop(context); onPressed: () {
}, bookProvider.filterBookByCategory(null);
); bookProvider.getBooks();
} context.pop();
return Container(); },
}, ),
), ],
),
),
Expanded(
child: ListView.builder(
itemCount: category != null ? category.length : 0,
itemBuilder: (context, index) {
if (category != null) {
return ListTile(
title: Text(category.elementAt(index).name),
onTap: () {
bookProvider.filterBookByCategory(
category!.elementAt(index).name);
bookProvider.getBooks();
Navigator.pop(context);
},
);
}
return Container();
},
),
),
],
), ),
), ),
); );
......
...@@ -27,9 +27,9 @@ class _BookList extends State<BookList> { ...@@ -27,9 +27,9 @@ class _BookList extends State<BookList> {
builder: (context, bookProvider, child) { builder: (context, bookProvider, child) {
if (!bookProvider.isLoading) { if (!bookProvider.isLoading) {
final Iterable<Book> books = bookProvider.books!.map((book) { final Iterable<Book> books = bookProvider.books!.map((book) {
if (book["category_detail"] != null) { if (book["category"] != null) {
final Category category = Category.fromJson( final Category category = Category.fromJson(
book["category_detail"], book["category"],
); );
return Book( return Book(
book["id"], book["id"],
...@@ -127,14 +127,9 @@ class _TopAppBar extends State<TopAppBar> { ...@@ -127,14 +127,9 @@ class _TopAppBar extends State<TopAppBar> {
leading: !showWidget leading: !showWidget
? IconButton( ? IconButton(
onPressed: () { onPressed: () {
if (category != null) { Scaffold.of(context).openDrawer();
bookProvider.filterBookByCategory(null);
bookProvider.getBooks();
} else {
Scaffold.of(context).openDrawer();
}
}, },
icon: Icon(category != null ? Icons.arrow_back : Icons.menu), icon: const Icon(Icons.menu),
) )
: null, : null,
elevation: 10.0, elevation: 10.0,
......
...@@ -91,7 +91,7 @@ class _LoanBookForm extends State<LoanBookForm> { ...@@ -91,7 +91,7 @@ class _LoanBookForm extends State<LoanBookForm> {
if (_formKey.currentState!.validate()) {} if (_formKey.currentState!.validate()) {}
authProvider authProvider
.createMemberLoan( .createMemberLoan(
authProvider.user!.accountId, authProvider.user!.id,
widget.bookId, widget.bookId,
int.parse(loanDayController.text), int.parse(loanDayController.text),
) )
......
...@@ -15,7 +15,8 @@ class ChangePasswordForm extends StatefulWidget { ...@@ -15,7 +15,8 @@ class ChangePasswordForm extends StatefulWidget {
class _ChangePasswordForm extends State<ChangePasswordForm> { class _ChangePasswordForm extends State<ChangePasswordForm> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final oldPasswordController = TextEditingController(); final oldPasswordController = TextEditingController();
final newPasswordController = TextEditingController(); final newPasswordController1 = TextEditingController();
final newPasswordController2 = TextEditingController();
bool passwordVisible = false; bool passwordVisible = false;
...@@ -28,7 +29,8 @@ class _ChangePasswordForm extends State<ChangePasswordForm> { ...@@ -28,7 +29,8 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
@override @override
void dispose() { void dispose() {
oldPasswordController.dispose(); oldPasswordController.dispose();
newPasswordController.dispose(); newPasswordController1.dispose();
newPasswordController2.dispose();
super.dispose(); super.dispose();
} }
...@@ -37,6 +39,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> { ...@@ -37,6 +39,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
Size screenSize = MediaQuery.of(context).size; Size screenSize = MediaQuery.of(context).size;
return Consumer<AuthProvider>(builder: (context, authProvider, child) { return Consumer<AuthProvider>(builder: (context, authProvider, child) {
final message = authProvider.message;
return Column( return Column(
children: [ children: [
Padding( Padding(
...@@ -79,7 +82,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> { ...@@ -79,7 +82,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
), ),
), ),
validator: (String? value) { validator: (String? value) {
if (value == null || value.isEmpty) { if (value == null) {
return "Please enter your old password"; return "Please enter your old password";
} else { } else {
return null; return null;
...@@ -88,7 +91,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> { ...@@ -88,7 +91,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
keyboardType: TextInputType.visiblePassword, keyboardType: TextInputType.visiblePassword,
), ),
TextFormField( TextFormField(
controller: newPasswordController, controller: newPasswordController1,
obscureText: passwordVisible, obscureText: passwordVisible,
decoration: InputDecoration( decoration: InputDecoration(
hintText: "Enter your New Password", hintText: "Enter your New Password",
...@@ -107,7 +110,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> { ...@@ -107,7 +110,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
), ),
), ),
validator: (String? value) { validator: (String? value) {
if (value == null || value.isEmpty) { if (value == null) {
return "Please enter your new password"; return "Please enter your new password";
} else { } else {
return null; return null;
...@@ -115,6 +118,24 @@ class _ChangePasswordForm extends State<ChangePasswordForm> { ...@@ -115,6 +118,24 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
}, },
keyboardType: TextInputType.visiblePassword, keyboardType: TextInputType.visiblePassword,
), ),
TextFormField(
controller: newPasswordController2,
decoration: const InputDecoration(
hintText: "Confirm your New Password",
labelText: "Confirm New Password",
),
validator: (String? value) {
if (value == null) {
return "Please enter your confirm new password";
} else {
return null;
}
},
),
Text(
message ?? "",
style: const TextStyle(color: Colors.red),
),
const SizedBox( const SizedBox(
height: 20.0, height: 20.0,
), ),
...@@ -127,9 +148,9 @@ class _ChangePasswordForm extends State<ChangePasswordForm> { ...@@ -127,9 +148,9 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
if (_formKey.currentState!.validate()) {} if (_formKey.currentState!.validate()) {}
authProvider.changePassword( authProvider.changePassword(
context, context,
authProvider.user!.accountId,
oldPasswordController.text, oldPasswordController.text,
newPasswordController.text, newPasswordController1.text,
newPasswordController2.text,
); );
}, },
child: authProvider.isLoading child: authProvider.isLoading
......
...@@ -43,6 +43,7 @@ class _ProfileEditForm extends State<ProfileEditForm> { ...@@ -43,6 +43,7 @@ class _ProfileEditForm extends State<ProfileEditForm> {
lastNameControler.text = user?.lastName ?? ""; lastNameControler.text = user?.lastName ?? "";
return Consumer<AuthProvider>(builder: (context, authProvider, child) { return Consumer<AuthProvider>(builder: (context, authProvider, child) {
final message = authProvider.message;
return Column( return Column(
children: [ children: [
Form( Form(
...@@ -62,6 +63,7 @@ class _ProfileEditForm extends State<ProfileEditForm> { ...@@ -62,6 +63,7 @@ class _ProfileEditForm extends State<ProfileEditForm> {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return "Please enter your username"; return "Please enter your username";
} }
return null; return null;
}, },
), ),
...@@ -75,6 +77,7 @@ class _ProfileEditForm extends State<ProfileEditForm> { ...@@ -75,6 +77,7 @@ class _ProfileEditForm extends State<ProfileEditForm> {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return "Please enter your email"; return "Please enter your email";
} }
return null; return null;
}, },
), ),
...@@ -92,6 +95,10 @@ class _ProfileEditForm extends State<ProfileEditForm> { ...@@ -92,6 +95,10 @@ class _ProfileEditForm extends State<ProfileEditForm> {
labelText: "Last Name", labelText: "Last Name",
), ),
), ),
Text(
message ?? "",
style: const TextStyle(color: Colors.red),
),
Padding( Padding(
padding: const EdgeInsets.only(top: 40.0), padding: const EdgeInsets.only(top: 40.0),
child: SizedBox( child: SizedBox(
...@@ -99,18 +106,15 @@ class _ProfileEditForm extends State<ProfileEditForm> { ...@@ -99,18 +106,15 @@ class _ProfileEditForm extends State<ProfileEditForm> {
child: FilledButton( child: FilledButton(
onPressed: () { onPressed: () {
if (_formKey.currentState!.validate()) {} if (_formKey.currentState!.validate()) {}
authProvider authProvider.updateUserDetail(
.updateUserDetail( context,
authProvider.user!.id, authProvider.user!.id,
usernameControler.text, usernameControler.text,
emailControler.text, emailControler.text,
firstNameControler.text, firstNameControler.text,
lastNameControler.text, lastNameControler.text,
authProvider.user!.isStaff, authProvider.user!.isStaff,
) );
.then(
(res) => Navigator.pop(context),
);
}, },
child: const Text("Submit"), child: const Text("Submit"),
), ),
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import 'package:library_app/src/providers/auth_provider.dart'; import 'package:library_app/src/providers/auth_provider.dart';
import 'package:library_app/src/screens/form_screen.dart';
import 'package:library_app/src/widgets/loading.dart'; import 'package:library_app/src/widgets/loading.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
...@@ -22,6 +22,8 @@ class _ResetPasswordForm extends State<ResetPasswordForm> { ...@@ -22,6 +22,8 @@ class _ResetPasswordForm extends State<ResetPasswordForm> {
const String formText = "Confirm your email to continue reset password"; const String formText = "Confirm your email to continue reset password";
return Consumer<AuthProvider>(builder: (context, authProvider, child) { return Consumer<AuthProvider>(builder: (context, authProvider, child) {
final message = authProvider.message;
return Column( return Column(
children: [ children: [
Container( Container(
...@@ -67,13 +69,14 @@ class _ResetPasswordForm extends State<ResetPasswordForm> { ...@@ -67,13 +69,14 @@ class _ResetPasswordForm extends State<ResetPasswordForm> {
validator: (String? value) { validator: (String? value) {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return "Please enter your email"; return "Please enter your email";
} else if (!value.contains("@")) {
return "Email should include '@'";
} }
return null; return null;
}, },
), ),
// Flutter, iwant to go to ConfirmResetPasswordScreen after authProvider.resetPassword succeed with response 200 Text(
message ?? "",
style: const TextStyle(color: Colors.red),
),
Container( Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
vertical: 20.0, vertical: 20.0,
...@@ -85,22 +88,8 @@ class _ResetPasswordForm extends State<ResetPasswordForm> { ...@@ -85,22 +88,8 @@ class _ResetPasswordForm extends State<ResetPasswordForm> {
child: FilledButton( child: FilledButton(
onPressed: () { onPressed: () {
if (_formKey.currentState!.validate()) {} if (_formKey.currentState!.validate()) {}
authProvider authProvider.resetPassword(
.resetPassword(emailController.text) context, emailController.text);
.then(
(response) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
const ConfirmResetPasswordScreen(),
),
);
},
).catchError(
(error) {
debugPrint('Exception: $error');
},
);
}, },
child: authProvider.isLoading child: authProvider.isLoading
? const Loading() ? const Loading()
...@@ -142,12 +131,7 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> { ...@@ -142,12 +131,7 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> {
const String formText = "Enter the pin that we just sent to your email"; const String formText = "Enter the pin that we just sent to your email";
return Consumer<AuthProvider>(builder: (context, authProvider, child) { return Consumer<AuthProvider>(builder: (context, authProvider, child) {
if (authProvider.isLoading) { final message = authProvider.message;
return const Center(
child: CircularProgressIndicator(),
);
}
return Column( return Column(
children: [ children: [
Container( Container(
...@@ -190,6 +174,17 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> { ...@@ -190,6 +174,17 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> {
labelText: "confirmation pin", labelText: "confirmation pin",
suffixIcon: Icon(Icons.password), suffixIcon: Icon(Icons.password),
), ),
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
validator: (String? value) {
if (value == null) {
return "Please enter your pin";
} else if (value is int) {
return "Please enter pin in number";
}
return null;
},
), ),
TextFormField( TextFormField(
controller: password1Controller, controller: password1Controller,
...@@ -241,12 +236,16 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> { ...@@ -241,12 +236,16 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> {
validator: (String? value) { validator: (String? value) {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return "Please enter your password"; return "Please enter your password";
} else {
return null;
} }
return null;
}, },
keyboardType: TextInputType.visiblePassword, keyboardType: TextInputType.visiblePassword,
), ),
Text(
message ?? "",
style: const TextStyle(color: Colors.red),
),
Container( Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
vertical: 20.0, vertical: 20.0,
...@@ -258,28 +257,16 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> { ...@@ -258,28 +257,16 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> {
child: FilledButton( child: FilledButton(
onPressed: () { onPressed: () {
if (_formKey.currentState!.validate()) {} if (_formKey.currentState!.validate()) {}
authProvider authProvider.confirmResetPassword(
.confirmResetPassword( context,
int.parse(pinController.text), int.parse(pinController.text),
password1Controller.text, password1Controller.text,
password2Controller.text, password2Controller.text,
)
.then(
(response) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
const LoginScreen(),
),
);
},
).catchError(
(error) {
debugPrint('Exception: $error');
},
); );
}, },
child: const Text("Submit"), child: authProvider.isLoading
? const Loading()
: const Text("Submit"),
), ),
), ),
], ],
......
...@@ -27,14 +27,16 @@ class _SearchForm extends State<SearchForm> { ...@@ -27,14 +27,16 @@ class _SearchForm extends State<SearchForm> {
hintText: "Enter keywords...", hintText: "Enter keywords...",
elevation: WidgetStateProperty.all(0), elevation: WidgetStateProperty.all(0),
onChanged: (value) { onChanged: (value) {
Future.delayed( if (value.length >= 3) {
Duration.zero, Future.delayed(
() { Duration.zero,
Provider.of<BookProvider>(context, listen: false) () {
.setSearchKeyword(value); Provider.of<BookProvider>(context, listen: false)
Provider.of<BookProvider>(context, listen: false).getBooks(); .setSearchKeyword(value);
}, Provider.of<BookProvider>(context, listen: false).getBooks();
); },
);
}
}, },
leading: const Icon(Icons.search), leading: const Icon(Icons.search),
), ),
......
...@@ -50,7 +50,6 @@ class _AdminLoanList extends State<AdminLoanList> { ...@@ -50,7 +50,6 @@ class _AdminLoanList extends State<AdminLoanList> {
var userData = memberData["user"]; var userData = memberData["user"];
var user = User( var user = User(
userData["id"], userData["id"],
memberData["id"],
userData["username"], userData["username"],
userData["email"], userData["email"],
userData["first_name"], userData["first_name"],
......
...@@ -32,7 +32,7 @@ class _LoanList extends State<LoanList> { ...@@ -32,7 +32,7 @@ class _LoanList extends State<LoanList> {
if (authProvider.memberLoans != null) { if (authProvider.memberLoans != null) {
var loans = authProvider.memberLoans!.map( var loans = authProvider.memberLoans!.map(
(loan) { (loan) {
var book = Book.fromJson(loan["book_detail"]); var book = Book.fromJson(loan["book"]);
return Loan( return Loan(
book, book,
null, null,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment