From 6b11d19f60c602e316fee4282baa74bfc7389945 Mon Sep 17 00:00:00 2001 From: Raghvind Yadav Date: Sun, 10 Dec 2023 16:30:07 +0530 Subject: [PATCH] create and delete --- lib/controllers/user_controller.dart | 38 ++++ lib/home_page.dart | 6 +- lib/main.dart | 21 +- lib/modal/user.dart | 4 +- lib/screens/admin_management.dart | 129 ++++++++++++ lib/screens/create_user.dart | 289 +++++++++++++++++++++++++++ lib/services/api_provider.dart | 37 +++- lib/splash.dart | 2 +- lib/web/drawer/drawer.dart | 27 ++- 9 files changed, 523 insertions(+), 30 deletions(-) create mode 100644 lib/screens/admin_management.dart create mode 100644 lib/screens/create_user.dart diff --git a/lib/controllers/user_controller.dart b/lib/controllers/user_controller.dart index a79dd9a..4aadb75 100644 --- a/lib/controllers/user_controller.dart +++ b/lib/controllers/user_controller.dart @@ -1,3 +1,6 @@ +import 'dart:convert'; + +import 'package:afghan_net/services/app_remote_routes.dart'; import 'package:get/get.dart'; import 'package:get_storage/get_storage.dart'; @@ -6,7 +9,10 @@ import '../services/api_provider.dart'; class UserController extends GetxController{ final apiProvider = ApiProvider(); + GetStorage sr = GetStorage(); late User user; + late List listUsers; + userLogin({required String email, required String pass}) async{ final data = await apiProvider.post("login",{"email":email,"password":pass}); user = User.fromJson(data); @@ -15,4 +21,36 @@ class UserController extends GetxController{ await sr.write("user", user); print(sr.read('user')); } + + Future createUser(Map userData)async{ + final data = await apiProvider.post('createUser', userData); + + print("message ${data['message']}"); + return data['message']; + } + + User getUser(){ + if(sr.read('user') is User){ + user = sr.read('user'); + }else{ + user = User.fromJson(sr.read('user')); + } + return user; + } + + deleteUser({required String userId}) async{ + final data = await apiProvider.delete("user", {"id":userId}); + print(data); + + } + + Future> getAllUsers()async{ + // listUsers.clear(); + final data = await apiProvider.get(AppRemoteRoutes.allUser); + final List listData = json.decode(jsonEncode(data['data'])); + listUsers = + listData.map((x)=>User.fromJson(x)).toList(); + return listUsers; + } + } \ No newline at end of file diff --git a/lib/home_page.dart b/lib/home_page.dart index 6cfe0d1..05cb537 100644 --- a/lib/home_page.dart +++ b/lib/home_page.dart @@ -1,7 +1,9 @@ import 'package:afghan_net/Afgan_List_UI/internet_bundle/vpn_plans/vpn_all.dart'; import 'package:afghan_net/Afgan_List_UI/status/dialog_box.dart'; import 'package:afghan_net/catagory.dart'; +import 'package:afghan_net/controllers/user_controller.dart'; import 'package:afghan_net/order.dart'; +import 'package:afghan_net/web/drawer/drawer.dart'; import 'package:afghan_net/widgets/tab_navigate.dart'; import 'package:afghan_net/widgets/text.dart'; import 'package:afghan_net/widgets/transaction.dart'; @@ -24,6 +26,8 @@ class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { + final userController = Get.find(); + userController.getUser(); return Scaffold( appBar: AppBar( title: Row( @@ -57,7 +61,7 @@ class HomePage extends StatelessWidget { ), ), key: _scaffoldKey, - drawer: All_Drawer(), + drawer: All_Drawer_Web(), body: SingleChildScrollView( child: Column(children: [ SizedBox( diff --git a/lib/main.dart b/lib/main.dart index 0caa785..043f70d 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,6 @@ import 'package:afghan_net/home_page.dart'; import 'package:afghan_net/login.dart'; +import 'package:afghan_net/screens/admin_management.dart'; import 'package:afghan_net/splash.dart'; import 'package:afghan_net/web/HomePageWeb.dart'; @@ -31,16 +32,16 @@ class MyApp extends StatelessWidget { } Widget _buildHomePage(double screenWidth, DeviceType deviceType) { - if (screenWidth < 400 || deviceType == DeviceType.mobile) { + // if (screenWidth < 400 || deviceType == DeviceType.mobile) { + // return Splash(); + // } else if (screenWidth < 400) { + // return Splash(); + // } else if (screenWidth >= 700 && screenWidth < 1024) { + // return Splash(); + // } else if (screenWidth >= 1024 && screenWidth <= 1920) { + // return Splash(); + // } else { return Splash(); - } else if (screenWidth < 400) { - return Splash(); - } else if (screenWidth >= 700 && screenWidth < 1024) { - return Splash(); - } else if (screenWidth >= 1024 && screenWidth <= 1920) { - return Splash(); - } else { - return Splash(); - } + // } } } diff --git a/lib/modal/user.dart b/lib/modal/user.dart index 7c55475..6578d96 100644 --- a/lib/modal/user.dart +++ b/lib/modal/user.dart @@ -13,7 +13,7 @@ class User { DateTime createdAt; DateTime updatedAt; int v; - String token; + String? token; User({ required this.id, @@ -30,7 +30,7 @@ class User { required this.createdAt, required this.updatedAt, required this.v, - required this.token, + this.token, }); factory User.fromJson(Map json) => User( diff --git a/lib/screens/admin_management.dart b/lib/screens/admin_management.dart new file mode 100644 index 0000000..251d0a9 --- /dev/null +++ b/lib/screens/admin_management.dart @@ -0,0 +1,129 @@ +import 'package:afghan_net/controllers/user_controller.dart'; +import 'package:afghan_net/screens/create_user.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; + +class AdminManagement extends StatefulWidget { + const AdminManagement({super.key}); + + @override + State createState() => _AdminManagementState(); +} + +class _AdminManagementState extends State { + final userController = Get.put(UserController()); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text("Admin Management"), + ), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Container( + decoration: BoxDecoration( + borderRadius: + const BorderRadius.all(Radius.circular(5)), + border: Border.all(color: Colors.green)), + child: ListTile( + leading: const Icon( + Icons.create, + color: Colors.green, + ), + title: const Text( + "Create User", + style: TextStyle( + color: Colors.green, fontWeight: FontWeight.bold), + ), + onTap: () { + Get.to(()=>CreateUser()); + }, + ), + ), + ), + const SizedBox( + width: 40, + ), + Expanded( + child: Container( + decoration: BoxDecoration( + borderRadius: + const BorderRadius.all(Radius.circular(5)), + border: Border.all(color: Colors.red)), + child: ListTile( + leading: const Icon( + Icons.delete, + color: Colors.red, + ), + title: const Text( + "Deleted User", + style: TextStyle(color: Colors.red), + ), + onTap: () { + // route for delete user page + }, + ), + ), + ), + ], + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 10.0), + child: FutureBuilder( + future: userController.getAllUsers(), + builder: (context, snapshot) { + if (snapshot.hasData) { + return ListView.builder( + itemCount: userController.listUsers.length, + shrinkWrap: true, + itemBuilder: (BuildContext context, int index) { + return Dismissible( + background: Container(color: Colors.red,), + onDismissed: (direction) async{ + await userController.deleteUser(userId: userController.listUsers[index].id); + + setState(() { + userController.listUsers.removeAt(index); + }); + + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('${userController.listUsers[index].firstName} deleted'), + ), + ); + }, + key: Key(userController.listUsers[index].id), + child: ListTile( + leading: const Icon(Icons.account_circle), + title: Text( + "${userController.listUsers[index].firstName} ${userController.listUsers[index].lastName}"), + subtitle: Text( + userController.listUsers[index].email ?? + userController.listUsers[index].mobile + .toString()), + trailing: Text( + userController.listUsers[index].userType), + ), + ); + }); + } + return const Center(child: CircularProgressIndicator()); + }), + ) + ], + ), + ), + ), + ); + } +} diff --git a/lib/screens/create_user.dart b/lib/screens/create_user.dart new file mode 100644 index 0000000..d8df110 --- /dev/null +++ b/lib/screens/create_user.dart @@ -0,0 +1,289 @@ +import 'package:afghan_net/controllers/user_controller.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; + +class CreateUser extends StatefulWidget { + const CreateUser({super.key}); + + @override + State createState() => _CreateUserState(); +} + +class _CreateUserState extends State { + String userType = ""; + String currencyType = ""; + final _formKey = GlobalKey(); + final firstName = TextEditingController(); + final lastName = TextEditingController(); + final email = TextEditingController(); + final mobile = TextEditingController(); + final district = TextEditingController(); + final province = TextEditingController(); + final password = TextEditingController(); + + final userController = Get.put(UserController()); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Create User'), + ), + body: SafeArea( + child: SingleChildScrollView( + child: Form( + key: _formKey, + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + TextFormField( + controller: firstName, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(5)), + hintText: "First Name", + label: const Text('First Name')), + validator: (value) { + if (value == null || value.isEmpty) { + return "Field can't be empty"; + } + return null; + }, + ), + const SizedBox( + height: 20, + ), + TextFormField( + controller: lastName, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(5)), + hintText: "Last Name", + label: const Text('Last Name')), + validator: (value) { + if (value == null || value.isEmpty) { + return "Field can't be empty"; + } + return null; + }, + ), + const SizedBox( + height: 20, + ), + TextFormField( + controller: email, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(5)), + hintText: "Email", + label: const Text('Email')), + validator: (value) { + if (value == null || value.isEmpty) { + return "Field can't be empty"; + } + return null; + }, + ), + const SizedBox( + height: 20, + ), + TextFormField( + controller: mobile, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(5)), + hintText: "Mobile with STD code", + label: const Text('Mobile')), + validator: (value) { + if (value == null || value.isEmpty) { + return "Field can't be empty"; + } + return null; + }, + ), + const SizedBox( + height: 20, + ), + TextFormField( + controller: district, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(5)), + hintText: "District", + label: const Text('District')), + validator: (value) { + if (value == null || value.isEmpty) { + return "Field can't be empty"; + } + return null; + }, + ), + const SizedBox( + height: 20, + ), + TextFormField( + controller: province, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(5)), + hintText: "Province", + label: const Text('Province')), + validator: (value) { + if (value == null || value.isEmpty) { + return "Field can't be empty"; + } + return null; + }, + ), + const SizedBox( + height: 20, + ), + TextFormField( + controller: password, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(5)), + hintText: "Password", + label: const Text('Password'), + suffixIcon: const Icon(Icons.password)), + validator: (value) { + if (value == null || value.isEmpty) { + return "Field can't be empty"; + } else if (value.length < 8) { + return "Please create a long password."; + } + return null; + }, + ), + const SizedBox( + height: 20, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + PopupMenuButton( + child: Container( + decoration: BoxDecoration( + border: Border.all( + color: Colors.blue, width: 1.5), + borderRadius: BorderRadius.circular(5)), + padding: const EdgeInsets.symmetric( + horizontal: 30, vertical: 10), + child: Text( + userType.isEmpty ? "User Type" : userType, + style: + TextStyle(fontSize: 18, color: Colors.blue), + ), + ), + onSelected: (String result) { + print("Selected: $result"); + setState(() { + userType = result; + }); + }, + itemBuilder: (BuildContext context) => + >[ + const PopupMenuItem( + value: 'Admin', + child: Text('Admin'), + ), + const PopupMenuItem( + value: 'Regular', + child: Text('Regular'), + ), + ], + ), + PopupMenuButton( + child: Container( + decoration: BoxDecoration( + border: Border.all( + color: Colors.green, width: 1.5), + borderRadius: BorderRadius.circular(5)), + padding: const EdgeInsets.symmetric( + horizontal: 30, vertical: 10), + child: Text( + currencyType.isEmpty + ? "Currency Type" + : currencyType, + style: TextStyle( + fontSize: 18, color: Colors.green), + ), + ), + onSelected: (String result) { + print("Selected: $result"); + setState(() { + currencyType = result; + }); + }, + itemBuilder: (BuildContext context) => + >[ + const PopupMenuItem( + value: 'AF', + child: Text('AF'), + ), + const PopupMenuItem( + value: 'IR', + child: Text('IR'), + ), + ], + ), + ], + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 20), + child: SizedBox( + height: 40, + width: 200, + child: ElevatedButton( + onPressed: () async{ + if (_formKey.currentState!.validate()) { + if (currencyType.isEmpty || + userType.isEmpty) { + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar( + content: Text( + 'Make user Currency & UserType is not empty.'))); + }else{ + final message = await userController.createUser({ + "firstName": firstName.text, + "lastName": lastName.text, + "email": email.text, + "mobile": mobile.text, + "district": lastName.text, + "province": province.text, + "password": password.text, + "userType": userType, + "currency": currencyType + }); + if(message == "User created successfully"){ + ScaffoldMessenger.of(context) + .showSnackBar( + SnackBar( + backgroundColor: Colors.green, + content: Text( + message,style: const TextStyle(color: Colors.white),))); + Future.delayed(Duration(seconds: 2),(){ + Navigator.pop(context,true); + }); + }else{ + ScaffoldMessenger.of(context) + .showSnackBar( + SnackBar( + backgroundColor: Colors.red, + content: Text( + message,style: const TextStyle(color: Colors.white),))); + } + } + } + }, + child: const Text("Create User"))), + ) + ]), + ), + ), + ), + )); + } +} diff --git a/lib/services/api_provider.dart b/lib/services/api_provider.dart index af631bc..06c82bc 100644 --- a/lib/services/api_provider.dart +++ b/lib/services/api_provider.dart @@ -38,17 +38,36 @@ class ApiProvider{ Future> get(String endPoint) async { try { - // GetStorage sr = GetStorage(); - // String? token = sr.read('token'); - // print(token); - // _dio.options.headers.addAll({'Authorization': 'Token $token'}); - + GetStorage sr = GetStorage(); + String? token = sr.read('token'); + print("token $token"); + _dio.options.headers.addAll({'authorization': token}); final Response response = await _dio.get( endPoint, ); - print(response); + print(response.data); - final Map responseData = classifyResponse(response); + final responseData = classifyResponse(response); + return responseData; + } on DioError catch (err) { + print(err); + return {}; + } + } + + Future> delete(String endPoint,Map body) async { + try { + GetStorage sr = GetStorage(); + String? token = sr.read('token'); + print("token $token"); + _dio.options.headers.addAll({'authorization': token}); + final Response response = await _dio.delete( + endPoint, + data: body, + ); + print(response.data); + + final responseData = classifyResponse(response); return responseData; } on DioError catch (err) { print(err); @@ -65,7 +84,7 @@ class ApiProvider{ String? token = sr.read('token'); print(token ?? ""); if (token != null) { - _dio.options.headers.addAll({'Authorization': 'Token $token'}); + _dio.options.headers.addAll({'authorization': token}); } final Response response = await _dio.post( endPoint, @@ -89,7 +108,7 @@ class ApiProvider{ GetStorage sr = GetStorage(); String? token = sr.read('token'); print(token ?? ""); - _dio.options.headers.addAll({'Authorization': 'Token $token'}); + _dio.options.headers.addAll({'authorization': token}); print("starting dio"); final Response response = await _dio.put( endPoint, diff --git a/lib/splash.dart b/lib/splash.dart index 7983522..198db53 100644 --- a/lib/splash.dart +++ b/lib/splash.dart @@ -9,7 +9,7 @@ class Splash extends StatelessWidget { @override Widget build(BuildContext context) { print("splash"); - Future.delayed(Duration(seconds: 3), () { + Future.delayed(Duration(seconds: 1), () { GetStorage sr = GetStorage(); final token = sr.read('token'); print(token); diff --git a/lib/web/drawer/drawer.dart b/lib/web/drawer/drawer.dart index f55418c..50d33b3 100644 --- a/lib/web/drawer/drawer.dart +++ b/lib/web/drawer/drawer.dart @@ -2,6 +2,8 @@ import 'package:afghan_net/Afgan_List_UI/internet_bundle/vpn_plans/vpn_all.dart' import 'package:afghan_net/Afgan_List_UI/status/dialog_box.dart'; import 'package:afghan_net/App_DrawerContents/reseller_management.dart'; import 'package:afghan_net/catagory.dart'; +import 'package:afghan_net/controllers/user_controller.dart'; +import 'package:afghan_net/screens/admin_management.dart'; import 'package:afghan_net/web/HomePageWeb.dart'; import 'package:afghan_net/web/catagory/catagory.dart'; import 'package:afghan_net/web/order_page.dart'; @@ -11,6 +13,8 @@ import 'package:afghan_net/widgets/transaction.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; +import '../../modal/user.dart'; + class All_Drawer_Web extends StatelessWidget { const All_Drawer_Web({ super.key, @@ -18,12 +22,14 @@ class All_Drawer_Web extends StatelessWidget { @override Widget build(BuildContext context) { + final userController = Get.find(); + final User user = userController.user; return Drawer( child: ListView( padding: const EdgeInsets.all(0), children: [ - const UserAccountsDrawerHeader( - decoration: BoxDecoration( + UserAccountsDrawerHeader( + decoration: const BoxDecoration( color: Colors.blue, image: DecorationImage( image: AssetImage("assets/drawerback.jpeg"), @@ -33,16 +39,16 @@ class All_Drawer_Web extends StatelessWidget { accountName: Padding( padding: EdgeInsets.only(top: 25), child: Text( - "Abhishek Mishra", - style: TextStyle(fontSize: 18), + "${user.firstName} ${user.lastName}", + style: const TextStyle(fontSize: 18), ), ), - accountEmail: Text("abhishekm977@gmail.com"), + accountEmail: Text(user.email!), currentAccountPictureSize: Size.square(50), currentAccountPicture: CircleAvatar( child: Text( - "A", - style: TextStyle(fontSize: 30.0), + user.firstName[0], + style:const TextStyle(fontSize: 30.0), ), ), ), @@ -95,6 +101,13 @@ class All_Drawer_Web extends StatelessWidget { Get.to(() => Reseller()); }, ), + ListTile( + leading: const Icon(Icons.manage_accounts), + title: const Text(' Admin management '), + onTap: () { + Get.to(() => AdminManagement()); + }, + ), ListTile( leading: const Icon(Icons.settings), title: const Text(' Settings '),