build_app

This commit is contained in:
risadmin_prod 2025-03-28 09:08:07 +00:00
parent 3470371d25
commit a602d61d2b
13 changed files with 3325 additions and 68 deletions

View File

@ -69,6 +69,9 @@ public class BuilderService {
executeDump(true);
// ADD OTHER SERVICE
addCustomMenu( "Testf", "Transcations");
System.out.println("dashboard and menu inserted...");

View File

@ -0,0 +1,195 @@
package com.realnet.basic1.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.realnet.config.EmailService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.domain.*;
import com.realnet.fnd.response.EntityResponse;
import org.springframework.http.*;
import org.springframework.beans.factory.annotation.*;
import com.realnet.basic1.Entity.Testf;
import com.realnet.basic1.Services.TestfService ;
@RequestMapping(value = "/Testf")
@CrossOrigin("*")
@RestController
public class TestfController {
@Autowired
private TestfService Service;
@Value("${projectPath}")
private String projectPath;
@PostMapping("/Testf")
public Testf Savedata(@RequestBody Testf data) {
Testf save = Service.Savedata(data) ;
System.out.println("data saved..." + save);
return save;
}
@PutMapping("/Testf/{id}")
public Testf update(@RequestBody Testf data,@PathVariable Integer id ) {
Testf update = Service.update(data,id);
System.out.println("data update..." + update);
return update;
}
// get all with pagination
@GetMapping("/Testf/getall/page")
public Page<Testf> getall(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "size", required = false) Integer size) {
Pageable paging = PageRequest.of(page, size);
Page<Testf> get = Service.getAllWithPagination(paging);
return get;
}
@GetMapping("/Testf")
public List<Testf> getdetails() {
List<Testf> get = Service.getdetails();
return get;
}
// get all without authentication
@GetMapping("/token/Testf")
public List<Testf> getallwioutsec() {
List<Testf> get = Service.getdetails();
return get;
}
@GetMapping("/Testf/{id}")
public Testf getdetailsbyId(@PathVariable Integer id ) {
Testf get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Testf/{id}")
public ResponseEntity<?> delete_by_id(@PathVariable Integer id ) {
Service.delete_by_id(id);
return new ResponseEntity<>(new EntityResponse("Deleted"), HttpStatus.OK);
}
}

View File

@ -0,0 +1,85 @@
package com.realnet.basic1.Entity;
import lombok.*;
import com.realnet.WhoColumn.Entity.Extension;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class Testf extends Extension {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private int numbers;
private String phones;
@Column(length = 2000)
private String paragraphs;
private String passwordss;
@Transient
private String confirmpasswordss;
@Column(length = 2000)
private String textareas;
private String dates;
private String datetimes;
private String emails;
private boolean toggless;
private String urls;
private int decimals;
private String recaptchas;
private int percentages;
private String documentss;
}

View File

@ -0,0 +1,54 @@
package com.realnet.basic1.Repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.*;
import com.realnet.basic1.Entity.Testf;
@Repository
public interface TestfRepository extends JpaRepository<Testf, Integer> {
@Query(value = "select * from testf where created_by=?1", nativeQuery = true)
List<Testf> findAll(Long creayedBy);
@Query(value = "select * from testf where created_by=?1", nativeQuery = true)
Page<Testf> findAll(Pageable page, Long creayedBy);
}

View File

@ -0,0 +1,214 @@
package com.realnet.basic1.Services;
import com.realnet.basic1.Repository.TestfRepository;
import com.realnet.basic1.Entity.Testf
;import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.realnet.SequenceGenerator.Service.SequenceService;
import com.realnet.Notification.Entity.NotificationService;
import org.springframework.data.domain.Page;
import com.realnet.realm.Entity.Realm;
import com.realnet.realm.Services.RealmService;
import org.springframework.data.domain.Pageable;
import org.springframework.http.*;import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.users.entity1.AppUser;
import org.springframework.stereotype.Service;
@Service
public class TestfService {
@Autowired
private TestfRepository Repository;
@Autowired
private AppUserServiceImpl userService;
@Autowired
private RealmService realmService;
@Autowired
private SequenceService documentsssequenceService;
public Testf Savedata(Testf data) {
data.setDocumentss (documentsssequenceService.GenerateSequence("s"));
data.setUpdatedBy(getUser().getUserId());
data.setCreatedBy(getUser().getUserId());
data.setAccountId(getUser().getAccount().getAccount_id());
Testf save = Repository.save(data);
return save;
}
// get all with pagination
public Page<Testf> getAllWithPagination(Pageable page) {
return Repository.findAll(page, getUser().getUserId());
}
public List<Testf> getdetails() {
List<Realm> realm = realmService.findByUserId(getUser().getUserId());
List<Testf> all = Repository.findAll(getUser().getUserId());
return all ; }
public Testf getdetailsbyId(Integer id) {
return Repository.findById(id).get();
}
public void delete_by_id(Integer id) {
Repository.deleteById(id);
}
public Testf update(Testf data,Integer id) {
Testf old = Repository.findById(id).get();
old.setName(data.getName());
old.setNumbers(data.getNumbers());
old.setPhones(data.getPhones());
old.setParagraphs(data.getParagraphs());
old.setPasswordss(data.getPasswordss());
old.setTextareas(data.getTextareas());
old.setDates(data.getDates());
old.setDatetimes(data.getDatetimes());
old.setEmails(data.getEmails());
old.setToggless (data.isToggless());
old.setUrls(data.getUrls());
old.setDecimals(data.getDecimals());
old.setRecaptchas(data.getRecaptchas());
old.setPercentages(data.getPercentages());
old.setDocumentss(data.getDocumentss());
final Testf test = Repository.save(old);
data.setUpdatedBy(getUser().getUserId());
return test;}
public AppUser getUser() {
AppUser user = userService.getLoggedInUser();
return user;
}}

View File

@ -0,0 +1,2 @@
CREATE TABLE db.Testf(id BIGINT NOT NULL AUTO_INCREMENT, percentages int, datetimes VARCHAR(400), dates Date, toggless VARCHAR(400), passwordss VARCHAR(400), textareas VARCHAR(400), urls VARCHAR(400), decimals int, name VARCHAR(400), numbers int, phones VARCHAR(400), documentss VARCHAR(400), recaptchas VARCHAR(400), emails VARCHAR(400), paragraphs VARCHAR(400), PRIMARY KEY (id));

View File

@ -0,0 +1,132 @@
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
import '../../../../resources/api_constants.dart';
import '../../../../data/network/base_network_service.dart';
import '../../../../data/network/network_api_service.dart';
class testfApiService {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<List<Map<String, dynamic>>> getEntities() async {
try {
final response = await _helper.getGetApiResponse('$baseUrl/Testf/Testf');
final entities = (response as List).cast<Map<String, dynamic>>();
return entities;
} catch (e) {
throw Exception('Failed to get all entities: $e');
}
}
Future<List<Map<String, dynamic>>> getAllWithPagination(
int page, int size) async {
try {
final response =
await _helper.getGetApiResponse('$baseUrl/Testf/Testf/getall/page?page=$page&size=$size');
final entities =
(response['content'] as List).cast<Map<String, dynamic>>();
return entities;
} catch (e) {
throw Exception('Failed to get all without pagination: $e');
}
}
Future<Map<String, dynamic>> createEntity(
Map<String, dynamic> entity) async {
try {
print("in post api$entity");
final response =
await _helper.getPostApiResponse('$baseUrl/Testf/Testf', entity);
print(entity);
// Assuming the response is a Map<String, dynamic>
Map<String, dynamic> responseData = response;
return responseData;
} catch (e) {
throw Exception('Failed to create entity: $e');
}
}
Future<void> updateEntity( int entityId, Map<String, dynamic> entity) async {
try {
await _helper.getPutApiResponse('$baseUrl/Testf/Testf/$entityId',
entity); print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity( int entityId) async {
try {
await _helper.getDeleteApiResponse('$baseUrl/Testf/Testf/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
}

View File

@ -0,0 +1,720 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import '../Testf_viewModel/Testf_view_model_screen.dart';
import '../../../../utils/image_constant.dart';
import '../../../../utils/size_utils.dart';
import '../../../../theme/app_style.dart';
import '../../../../widgets/app_bar/appbar_image.dart';
import '../../../../widgets/app_bar/appbar_title.dart';
import '../../../../widgets/app_bar/custom_app_bar.dart';
import '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart';
import '../../../../widgets/custom_dropdown_field.dart';
import 'dart:math';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:barcode_widget/barcode_widget.dart';
import 'package:intl/intl.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart'
;import 'package:multi_select_flutter/multi_select_flutter.dart';
import 'package:just_audio/just_audio.dart';
import 'package:video_player/video_player.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:lottie/lottie.dart';
import '../../../../utils/toast_messages/toast_message_util.dart';
import 'dart:io';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';
class testfCreateEntityScreen extends StatefulWidget {
const testfCreateEntityScreen({super.key});
@override
_testfCreateEntityScreenState createState() => _testfCreateEntityScreenState();
}
class _testfCreateEntityScreenState extends State<testfCreateEntityScreen> {
final Map<String, dynamic> formData = {};
final _formKey = GlobalKey<FormState>();
final TextEditingController nameController = TextEditingController();
final TextEditingController numbersController = TextEditingController();
final TextEditingController phonesController = TextEditingController();
final TextEditingController paragraphsController = TextEditingController();
bool _passwordVisiblepasswordss = false;
bool _isPasswordValidpasswordss = true;
bool _doPasswordsMatchpasswordss = true;
String _passwordpasswordss = ''; // To store the first password
void _validatePasswordpasswordss(String password) {
setState(() {
_isPasswordValidpasswordss = password.isNotEmpty;
_passwordpasswordss = password; // Store the password for later comparison
_doPasswordsMatchpasswordss = true; // Reset match flag on new input
});
}
void _validateConfirmPasswordpasswordss(String confirmPassword) {
setState(() {
_doPasswordsMatchpasswordss = confirmPassword == _passwordpasswordss;
});
}
final TextEditingController textareasController = TextEditingController();
TextEditingController dates = TextEditingController();
DateTime selectedDatedates = DateTime.now();
Future<void> _selectDatedates(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDatedates,
firstDate: DateTime(2000),
lastDate: DateTime(2101),
);
if (picked != null && picked != selectedDatedates) {
setState(() {
selectedDatedates = picked;
});
}
}
final TextEditingController datetimesController = TextEditingController();
bool _isemailsEmailValid = true;
void _validateemailsEmail(String email) {
setState(() {
_isemailsEmailValid = RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$').hasMatch(email);
});
}
bool _isSwitchedtoggless = false;
bool toggless = false;
void _toggleSwitchtoggless(bool value) {
setState(() {
_isSwitchedtoggless = value;
});
}
bool _isUrlValidurls = true;
void _validateUrlurls(String url) {
setState(() {
_isUrlValidurls = Uri.parse(url).isAbsolute;
});
}
final TextEditingController decimalsController = TextEditingController();
late String recaptchascaptcha;
TextEditingController _recaptchasController = TextEditingController();
final GlobalKey<ScaffoldMessengerState> _recaptchasscaffoldKey = GlobalKey<ScaffoldMessengerState>();
void generaterecaptchasCaptcha() {
final random = Random();
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
recaptchascaptcha = String.fromCharCodes(Iterable.generate(
6, (_) => chars.codeUnitAt(random.nextInt(chars.length))));
}
void verifyrecaptchasCaptcha() {
print("Verifying captcha");
if (_recaptchasController.text.isEmpty) {
print("recaptchas is empty");
recaptchasSnackbar('Please enter CAPTCHA', success: false);
} else if (_recaptchasController.text != recaptchascaptcha) {
print("captcha is not matching");
recaptchasSnackbar('CAPTCHA verification failed', success: false);
} else {
print("captcha is verified");
recaptchasSnackbar('CAPTCHA Verified', success: true);
// Navigate to another screen after verification
// Example navigation to a new screen
// Navigator.push(
// context,
// MaterialPageRoute(builder: (context) => NextScreen()),
// );
}
}
void recaptchasSnackbar(String message, {required bool success}) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: success ? Colors.green : Colors.red,
),
);
}
final TextEditingController percentagesController = TextEditingController();
@override
void initState() {
super.initState();
final provider = Provider.of<TestfViewModelScreen>(context, listen: false);
generaterecaptchasCaptcha();
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<TestfViewModelScreen>(context, listen: false);
return Scaffold(
appBar: CustomAppBar(
height: getVerticalSize(49),
leadingWidth: 40,
leading: AppbarImage(
height: getSize(24),
width: getSize(24),
svgPath: ImageConstant.imgArrowleftBlueGray900,
margin: getMargin(left: 16, top: 12, bottom: 13),
onTap: () {
Navigator.pop(context);
}),
centerTitle: true,
title: AppbarTitle(text: "Create Testf"),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
ReusableTextField(
controller: nameController,
onSaved:(value) => formData['name'] = value ,
label:"Enter Name",
// ValidationProperties
),
SizedBox(height: 16),
ReusableTextField(
controller: numbersController,
onSaved:(value) => formData['numbers'] = value ,
label: "Enter Numbers",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
// ValidationProperties
),
SizedBox(height: 16),
ReusableTextField(
onSaved:(value) => formData['phones'] = value ,
label: "Enter Phones",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(
10), // Limit input to 10 digits
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Phones';
}
if (value.length != 10) {
return 'Phone number must be exactly 10 digits';
}
return null;
},
),
ReusableTextField(
controller: paragraphsController,
onSaved:(value) => formData['paragraphs'] = value ,
label: "Enter Paragraphs",
maxLines: 5,
),
TextFormField(
obscureText: !_passwordVisiblepasswordss,
decoration: InputDecoration(
labelText: 'Passwordss',
suffixIcon: IconButton(
icon: Icon(
_passwordVisiblepasswordss
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
setState(() {
_passwordVisiblepasswordss = !_passwordVisiblepasswordss;
});
},
),
errorText:
_isPasswordValidpasswordss ? null : 'Please enter a password',
border: OutlineInputBorder(),
),
onSaved: (value) => formData['passwordss'] = value,
onChanged: _validatePasswordpasswordss,
),
const SizedBox(height: 16),
TextFormField(
obscureText: !_passwordVisiblepasswordss,
decoration: InputDecoration(
labelText: 'Confirm Passwordss',
suffixIcon: IconButton(
icon: Icon(
_passwordVisiblepasswordss
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
setState(() {
_passwordVisiblepasswordss = !_passwordVisiblepasswordss;
});
},
),
errorText:
_doPasswordsMatchpasswordss ? null : 'Passwords do not match',
border: OutlineInputBorder(),
),
onChanged: _validateConfirmPasswordpasswordss,
),
ReusableTextField(
controller: textareasController,
onSaved:(value) => formData['textareas'] = value ,
label: "Enter Textareas",
maxLines: 5,
// ValidationProperties
),
SizedBox(height: 16),
ReusableDatePickerField(
label:' Dates', controller: dates
,
onSaved: (value) => formData['dates'] = value,),
const SizedBox(height: 16),
ReusableTextField(
controller: datetimesController,
onSaved:(value) => formData['datetimes'] = value ,
label:"Enter Datetimes",
// ValidationProperties
),
SizedBox(height: 16),
Padding(
padding: getPadding(top: 19),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text("Emails",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900),
CustomTextFormField(
hintText: "Enter Emails",
errorText: _isemailsEmailValid ? null : 'Please enter a valid email',
onsaved: (value) => formData['emails'] = value,
onChanged: (value) {
_validateemailsEmail(value);
},
margin: getMargin(top: 6))
])),
Switch(
value: _isSwitchedtoggless,
onChanged: _toggleSwitchtoggless,
activeColor: Colors.white,
activeTrackColor: Colors.green,
inactiveThumbColor: Colors.white,
inactiveTrackColor: Colors.red,
),
Padding(
padding: getPadding(top: 19),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text("Urls",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900),
CustomTextFormField(
hintText: "Enter Urls",
errorText: _isUrlValidurls ? null : 'Please enter a valid URL',
keyboardType: TextInputType.url,
onsaved: (value) => formData['urls'] = value,
onChanged: _validateUrlurls,
margin: getMargin(top: 6))
])),
SizedBox(height: 16),
ReusableTextField(
controller: decimalsController,
onSaved:(value) => formData['decimals'] = value ,
label: "Enter Decimals",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
// ValidationProperties
),
SizedBox(height: 16),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'Enter the following CAPTCHA:',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
SizedBox(height: 16),
Container(
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
recaptchascaptcha,
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.blue,
letterSpacing: 4,
fontFamily: 'Roboto',
decoration: TextDecoration.none,
),
),
IconButton(
icon: Icon(Icons.refresh),
onPressed: () {
setState(() {
generaterecaptchasCaptcha();
});
},
),
],
),
),
SizedBox(height: 24),
TextFormField(
controller: _recaptchasController,
decoration: InputDecoration(
labelText: 'Enter CAPTCHA',
border: OutlineInputBorder(),
),
),
SizedBox(height: 24),
ElevatedButton(
onPressed: verifyrecaptchasCaptcha,
child: Text('Verify CAPTCHA'),
),
],
),
),
ReusableTextField(
controller: percentagesController,
onSaved:(value) => formData['percentages'] = value ,
label: "Enter Percentages",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
// ValidationProperties
),
SizedBox(height: 16),
const SizedBox(width: 8),
CustomButton(
height: getVerticalSize(50),
text: "Submit",
margin: getMargin(top: 24, bottom: 5),
onTap: () async {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
formData['toggless'] = toggless;
try {
print(formData);
Map<String, dynamic> createdEntity = await provider.createEntity(formData);
Navigator.pop(context);
} catch (e) {
// ignore: use_build_context_synchronously
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('Failed to create Testf: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
},
),
],
),
),
),
),
);
}
}

View File

@ -0,0 +1,589 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Testf_viewModel/Testf_view_model_screen.dart';
import '../../../../utils/image_constant.dart';
import '../../../../utils/size_utils.dart';
import '../../../../theme/app_style.dart';
import '../../../../widgets/app_bar/appbar_image.dart';
import '../../../../widgets/app_bar/appbar_title.dart';
import '../../../../widgets/app_bar/custom_app_bar.dart';
import 'package:barcode_widget/barcode_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:intl/intl.dart';
import 'dart:math';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';
import 'package:flutter/services.dart';
class testfUpdateEntityScreen extends StatefulWidget {
final Map<String, dynamic> entity;
testfUpdateEntityScreen({required this.entity});
@override
_testfUpdateEntityScreenState createState() => _testfUpdateEntityScreenState();
}
class _testfUpdateEntityScreenState extends State<testfUpdateEntityScreen> {
final _formKey = GlobalKey<FormState>();
bool _passwordVisiblepasswordss = false;
bool _isPasswordValidpasswordss = true;
bool _doPasswordsMatchpasswordss = true;
String _passwordpasswordss = ''; // To store the first password
void _validatePasswordpasswordss(String password) {
setState(() {
_isPasswordValidpasswordss = password.isNotEmpty;
_passwordpasswordss = password; // Store the password for later comparison
_doPasswordsMatchpasswordss = true; // Reset match flag on new input
});
}
void _validateConfirmPasswordpasswordss(String confirmPassword) {
setState(() {
_doPasswordsMatchpasswordss = confirmPassword == _passwordpasswordss;
});
}
TextEditingController dates = TextEditingController();
DateTime selectedDatedates = DateTime.now();
Future<void> _selectDatedates(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDatedates,
firstDate: DateTime(2000),
lastDate: DateTime(2101),
);
print(picked);
if (picked != null && picked != selectedDatedates) {
setState(() {
selectedDatedates = picked;
});
}
}
bool _isemailsEmailValid = true;
void _validateemailsEmail(String email) {
setState(() {
_isemailsEmailValid = RegExp(r'^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$').hasMatch(email);
});
}
bool istoggless = false;
bool _isUrlValidurls = true;
void _validateUrlurls(String url) {
setState(() {
_isUrlValidurls= Uri.parse(url).isAbsolute;
});
}
@override
void initState() {
super.initState();
final provider = Provider.of<TestfViewModelScreen>(context, listen: false);
istoggless = widget.entity['toggless'] ?? false; // Set initial value
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<TestfViewModelScreen>(context, listen: false);
return Scaffold(
appBar: CustomAppBar(
height: getVerticalSize(49),
leadingWidth: 40,
leading: AppbarImage(
height: getSize(24),
width: getSize(24),
svgPath: ImageConstant.imgArrowleftBlueGray900,
margin: getMargin(left: 16, top: 12, bottom: 13),
onTap: () {
Navigator.pop(context);
}),
centerTitle: true,
title: AppbarTitle(text: "Update Testf"), actions: [
],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
ReusableTextField(
label: "Please Enter Name",
initialValue: widget.entity['name'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['name'] = value,
),
SizedBox(height: 16),
ReusableTextField(
initialValue: widget.entity['numbers'].toString(),
onSaved: (value) => widget.entity['numbers']= value,
label: "Enter Numbers",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a number';
}
return null;
},
),
ReusableTextField(
initialValue: widget.entity['phones'],
onSaved: (value) => widget.entity['phones'] = value,
label: "Enter Phones",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(
10), // Limit input to 10 digits
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Phones';
}
if (value.length != 10) {
return 'Phone number must be exactly 10 digits';
}
return null;
},
),
// }),
ReusableTextField(
initialValue: widget.entity['paragraphs'],
onSaved: (value) => widget.entity['paragraphs']= value,
label: "Enter Paragraphs",
maxLines: 5,
),
TextFormField(
initialValue: widget.entity['passwordss'],
obscureText: !_passwordVisiblepasswordss,
decoration: InputDecoration(
labelText: 'Passwordss',
suffixIcon: IconButton(
icon: Icon(
_passwordVisiblepasswordss
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
setState(() {
_passwordVisiblepasswordss = !_passwordVisiblepasswordss;
});
},
),
errorText:
_isPasswordValidpasswordss ? null : 'Please enter a password',
border: OutlineInputBorder(),
),
onSaved: (value) => widget.entity['passwordss'] = value,
onChanged: _validatePasswordpasswordss,
),
const SizedBox(height: 16),
TextFormField(
obscureText: !_passwordVisiblepasswordss,
decoration: InputDecoration(
labelText: 'Confirm Passwordss',
suffixIcon: IconButton(
icon: Icon(
_passwordVisiblepasswordss
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
setState(() {
_passwordVisiblepasswordss = !_passwordVisiblepasswordss;
});
},
),
errorText:
_doPasswordsMatchpasswordss ? null : 'Passwords do not match',
border: OutlineInputBorder(),
),
onChanged: _validateConfirmPasswordpasswordss,
),
ReusableTextField(
initialValue: widget.entity['textareas'],
onSaved: (value) => widget.entity['textareas']= value,
label: "Enter Textareas",
maxLines: 5,
),
ReusableDatePickerField(label: 'Dates', controller: dates, initialDate: widget.entity['dates'],
onSaved: (value) => widget.entity['dates'] = value,),
ReusableTextField(
label: "Please Enter Datetimes",
initialValue: widget.entity['datetimes'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['datetimes'] = value,
),
SizedBox(height: 16),
Padding(
padding: getPadding(top: 19),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text("Emails",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle
.txtGilroyMedium16Bluegray900),
CustomTextFormField(
hintText: "Enter Emails",
initialValue: widget.entity['emails'],
keyboardType: TextInputType.url,
errorText: _isemailsEmailValid ? null : 'Please enter a valid URL',
onChanged: _validateemailsEmail,
// ValidationProperties
onsaved: (value) {
widget.entity['emails'] = value;
},
margin: getMargin(top: 6))
])),
SizedBox(height: 16),
Row(
children: [
Switch(
value: istoggless,
onChanged: (newValue) {
setState(() {
istoggless = newValue;
});
},
activeColor: Colors.white,
activeTrackColor: Colors.green,
inactiveThumbColor: Colors.white,
inactiveTrackColor: Colors.red,
),
const SizedBox(width: 8),
const Text('toggless'),
],
),
Padding(
padding: getPadding(top: 19),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text("Urls",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle
.txtGilroyMedium16Bluegray900),
CustomTextFormField(
hintText: "Enter Urls",
initialValue: widget.entity['urls'],
keyboardType: TextInputType.url,
errorText: _isUrlValidurls ? null : 'Please enter a valid URL',
onChanged: _validateUrlurls,
// ValidationProperties
onsaved: (value) {
widget.entity['urls'] = value;
},
margin: getMargin(top: 6))
])),
SizedBox(height: 16),
ReusableTextField(
initialValue: widget.entity['decimals'].toString(),
onSaved: (value) => widget.entity['decimals']= value,
label: "Enter Decimals",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a number';
}
return null;
},
),
ReusableTextField(
label: "Please Enter recaptchas",
initialValue: widget.entity['recaptchas'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['recaptchas'] = value,
),
SizedBox(height: 16),
ReusableTextField(
initialValue: widget.entity['percentages'].toString(),
onSaved: (value) => widget.entity['percentages']= value,
label: "Enter Percentages",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a number';
}
return null;
},
),
ReusableTextField(
label: "Please Enter documentss",
initialValue: widget.entity['documentss'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['documentss'] = value,
),
SizedBox(height: 16),
CustomButton(
height: getVerticalSize(50),
text: "Update",
margin: getMargin(top: 24, bottom: 5),
onTap: () async {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
widget.entity['toggless'] = istoggless;
try {
await provider.updateEntity(
widget.entity[
'id'], // Assuming 'id' is the key in your entity map
widget.entity);
Navigator.pop(context);
} catch (e) {
// ignore: use_build_context_synchronously
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content:
Text('Failed to update Testf: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
},
),
],
),
),
),
),
);
}
}

View File

@ -0,0 +1,92 @@
import 'package:dio/dio.dart';
import '../../../../data/network/base_network_service.dart';
import '../../../../data/network/network_api_service.dart';
import '../../../../resources/api_constants.dart';
class TestfRepoScreen {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<dynamic> getEntities() async {
try {
final response =
await _helper.getGetApiResponse('$baseUrl/Testf/Testf');
return response;
} catch (e) {
throw Exception('Failed to get all entities: $e');
}
}
Future<dynamic> getAllWithPagination(int page, int size) async {
try {
final response = await _helper.getGetApiResponse(
'$baseUrl/Testf/Testf/getall/page?page=$page&size=$size');
return response;
} catch (e) {
throw Exception('Failed to get all without pagination: $e');
}
}
Future<dynamic> createEntity(Map<String, dynamic> entity) async {
try {
print("in post api$entity");
final response = await _helper.getPostApiResponse(
'$baseUrl/Testf/Testf', entity);
print(entity);
return response;
} catch (e) {
throw Exception('Failed to create entity: $e');
}
}
Future<void> updateEntity(int entityId, Map<String, dynamic> entity) async {
try {
await _helper.getPutApiResponse(
'$baseUrl/Testf/Testf/$entityId', entity);
print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity(int entityId) async {
try {
await _helper
.getDeleteApiResponse('$baseUrl/Testf/Testf/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
}

View File

@ -0,0 +1,131 @@
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
import '../../../../utils/toast_messages/toast_message_util.dart';
import 'package:flutter/material.dart';
import '../Testf_Repo/Testf_repo_screen.dart';
class TestfViewModelScreen extends ChangeNotifier{
final TestfRepoScreen repo = TestfRepoScreen();
Future<List<Map<String, dynamic>>> getEntities() async {
try {
final response = await repo.getEntities();
final entities = (response as List).cast<Map<String, dynamic>>();
return entities;
} catch (e) {
throw Exception('Failed to get all entities: $e');
}
}
Future<List<Map<String, dynamic>>> getAllWithPagination(
int page, int size) async {
try {
final response =
await repo.getAllWithPagination(page, size); // Use await
print('res - $response');
// Ensure response is a Map<String, dynamic>
if (response is! Map<String, dynamic>) {
throw Exception('Unexpected response format: $response');
}
// Extract 'content' and ensure it's a list
final entities = (response['content'] as List)
.cast<Map<String, dynamic>>() // Ensure list of maps
.toList();
return entities;
} catch (e) {
print(e);
throw Exception('Failed to get all without pagination :- $e');
}
}
Future<Map<String, dynamic>> createEntity(Map<String, dynamic> entity) async {
try {
print("in post api - $entity");
// Wait for API response
final responseData =
await repo.createEntity(entity) as Map<String, dynamic>;
print('after value - $responseData');
ToastMessageUtil.showToast(
message: "Added Successfully", toastType: ToastType.success);
return responseData; // Return the data AFTER it is received
} catch (error) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Got Error", toastType: ToastType.error);
throw Exception(
'Failed to Create Entity: $error'); // Properly rethrow the error
}
}
Future<void> updateEntity(int entityId, Map<String, dynamic> entity) async {
try {
repo.updateEntity(entityId, entity).then((value) {
ToastMessageUtil.showToast(
message: "Updated Successfully", toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Got Error", toastType: ToastType.error);
},
);
print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity(int entityId) async {
try {
repo.deleteEntity(entityId).then((value) {
ToastMessageUtil.showToast(
message: "Deleted Successfully", toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Got Error", toastType: ToastType.error);
},
);
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
}

View File

@ -1,3 +1,6 @@
import '../../Entity/basic1/Testf/TestfView/Testf_entity_list_screen.dart';
import '../../Entity/basic1/Testf/Testf_viewModel/Testf_view_model_screen.dart';
import 'package:base_project/utils/image_constant.dart';
import 'package:base_project/commans/widgets/custome_drawe_item.dart';
import 'package:base_project/resources/app_colors.dart';
@ -9,79 +12,96 @@ import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
class MyCustomDrawer extends StatelessWidget {
const MyCustomDrawer({super.key});
const MyCustomDrawer({super.key});
@override
Widget build(BuildContext context) {
final email = UserManager().email;
final userName = UserManager().userName;
final provider = Provider.of<ProfileViewModel>(context, listen: false);
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
decoration: const BoxDecoration(
color: AppColors.primary,
),
currentAccountPicture: CircleAvatar(
radius: 60,
backgroundColor: AppColors.primary.withOpacity(0.3),
backgroundImage: provider.profileImageBytes != null
? MemoryImage(provider.profileImageBytes!)
: null,
child: provider.profileImageBytes != null
? null // Use backgroundImage for the actual image, so child should be null
: SvgPicture.asset(
ImageConstant.userProfileImg, // Placeholder SVG asset
@override
Widget build(BuildContext context) {
final email = UserManager().email;
final userName = UserManager().userName;
final provider = Provider.of<ProfileViewModel>(context, listen: false);
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
decoration: const BoxDecoration(
color: AppColors.primary,
),
currentAccountPicture: CircleAvatar(
radius: 60,
backgroundColor: AppColors.primary.withOpacity(0.3),
backgroundImage: provider.profileImageBytes != null
? MemoryImage(provider.profileImageBytes!)
: null,
child: provider.profileImageBytes != null
? null // Use backgroundImage for the actual image, so child should be null
: SvgPicture.asset(
ImageConstant.userProfileImg, // Placeholder SVG asset
// AppImages.userProfileImg, // Placeholder SVG asset
width: 60, // Adjust to fit the CircleAvatar
height: 60,
),
),
accountName: Text("Hello, $userName"),
accountEmail: Text(email.toString()),
),
DrawerItem(
color: AppColors.primary,
icon: Icons.person,
title: 'Profile',
onTap: () {
Navigator.pushNamed(context, RouteNames.profileView);
},
),
DrawerItem(
color: AppColors.primary,
icon: Icons.system_security_update,
title: 'System Parameters',
onTap: () {
width: 60, // Adjust to fit the CircleAvatar
height: 60,
),
),
accountName: Text("Hello, $userName"),
accountEmail: Text(email.toString()),
),
DrawerItem(
color: AppColors.primary,
icon: Icons.person,
title: 'Profile',
onTap: () {
Navigator.pushNamed(context, RouteNames.profileView);
},
),
DrawerItem(
color: AppColors.primary,
icon: Icons.system_security_update,
title: 'System Parameters',
onTap: () {
// Add navigation or other logic here
Navigator.pushNamed(context, RouteNames.systemParamsView);
},
),
DrawerItem(
color: AppColors.primary,
icon: Icons.password,
title: 'change password',
onTap: () {
Navigator.pushNamed(context, RouteNames.changePasswordView);
},
),
Navigator.pushNamed(context, RouteNames.systemParamsView);
},
),
DrawerItem(
color: AppColors.primary,
icon: Icons.password,
title: 'change password',
onTap: () {
Navigator.pushNamed(context, RouteNames.changePasswordView);
},
),
// NEW MENU
DrawerItem(
icon: Icons.logout,
color: Colors.red,
title: 'Logout',
onTap: () async {
await UserManager().clearUser();
Navigator.pushReplacementNamed(context, RouteNames.splashView);
},
DrawerItem(
color: AppColors.primary,
icon: Icons.chat_bubble,
title: 'Testf',
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => TestfViewModelScreen(),
child: testf_entity_list_screen(),
),
),
);
},
),
],
),
);
}
DrawerItem(
icon: Icons.logout,
color: Colors.red,
title: 'Logout',
onTap: () async {
await UserManager().clearUser();
Navigator.pushReplacementNamed(context, RouteNames.splashView);
},
),
],
),
);
}
}