build_app

This commit is contained in:
risadmin_prod 2025-03-29 06:26:25 +00:00
parent 4800cec522
commit e4d166f2b7
26 changed files with 4062 additions and 68 deletions

View File

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

View File

@ -0,0 +1,83 @@
package com.realnet.forma.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.forma.Entity.Child;
import com.realnet.forma.Services.ChildService ;
@RequestMapping(value = "/Child")
@CrossOrigin("*")
@RestController
public class ChildController {
@Autowired
private ChildService Service;
@Value("${projectPath}")
private String projectPath;
@PostMapping("/Child")
public Child Savedata(@RequestBody Child data) {
Child save = Service.Savedata(data) ;
System.out.println("data saved..." + save);
return save;
}
@PutMapping("/Child/{id}")
public Child update(@RequestBody Child data,@PathVariable Integer id ) {
Child update = Service.update(data,id);
System.out.println("data update..." + update);
return update;
}
// get all with pagination
@GetMapping("/Child/getall/page")
public Page<Child> getall(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "size", required = false) Integer size) {
Pageable paging = PageRequest.of(page, size);
Page<Child> get = Service.getAllWithPagination(paging);
return get;
}
@GetMapping("/Child")
public List<Child> getdetails() {
List<Child> get = Service.getdetails();
return get;
}
// get all without authentication
@GetMapping("/token/Child")
public List<Child> getallwioutsec() {
List<Child> get = Service.getdetails();
return get;
}
@GetMapping("/Child/{id}")
public Child getdetailsbyId(@PathVariable Integer id ) {
Child get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Child/{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,139 @@
package com.realnet.forma.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.forma.Entity.Testm;
import com.realnet.forma.Services.TestmService ;
@RequestMapping(value = "/Testm")
@CrossOrigin("*")
@RestController
public class TestmController {
@Autowired
private TestmService Service;
@Value("${projectPath}")
private String projectPath;
@PostMapping("/Testm")
public Testm Savedata(@RequestBody Testm data) {
Testm save = Service.Savedata(data) ;
System.out.println("data saved..." + save);
return save;
}
@PutMapping("/Testm/{id}")
public Testm update(@RequestBody Testm data,@PathVariable Integer id ) {
Testm update = Service.update(data,id);
System.out.println("data update..." + update);
return update;
}
// get all with pagination
@GetMapping("/Testm/getall/page")
public Page<Testm> getall(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "size", required = false) Integer size) {
Pageable paging = PageRequest.of(page, size);
Page<Testm> get = Service.getAllWithPagination(paging);
return get;
}
@GetMapping("/Testm")
public List<Testm> getdetails() {
List<Testm> get = Service.getdetails();
return get;
}
// get all without authentication
@GetMapping("/token/Testm")
public List<Testm> getallwioutsec() {
List<Testm> get = Service.getdetails();
return get;
}
@GetMapping("/Testm/{id}")
public Testm getdetailsbyId(@PathVariable Integer id ) {
Testm get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Testm/{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,24 @@
package com.realnet.forma.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.realnet.forma.Entity.Testm_ListFilter1;
import com.realnet.forma.Services.Testm_ListFilter1Service ;
@RequestMapping(value = "/Testm_ListFilter1")
@RestController
public class Testm_ListFilter1Controller {
@Autowired
private Testm_ListFilter1Service Service;
@GetMapping("/Testm_ListFilter1")
public List<Testm_ListFilter1> getlist() {
List<Testm_ListFilter1> get = Service.getlistbuilder();
return get;
}
@GetMapping("/Testm_ListFilter11")
public List<Testm_ListFilter1> getlistwithparam( ) {
List<Testm_ListFilter1> get = Service.getlistbuilderparam( );
return get;
}
}

View File

@ -0,0 +1,24 @@
package com.realnet.forma.Entity;
import lombok.*;
import com.realnet.WhoColumn.Entity.Extension;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class Child extends Extension {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String namemmm;
}

View File

@ -0,0 +1,64 @@
package com.realnet.forma.Entity;
import lombok.*;
import com.realnet.WhoColumn.Entity.Extension;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
import com.realnet.forma.Entity.Child;
@Entity
@Data
public class Testm extends Extension {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String namem;
private String bar_code;
private String qr_code;
@OneToOne( cascade=CascadeType.ALL)
private Child child;
private int numberm;
private int numberb;
private String calculatedgg;
}

View File

@ -0,0 +1,14 @@
package com.realnet.forma.Entity;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Data
public class Testm_ListFilter1 {
private Integer id;
private String namem;
}

View File

@ -0,0 +1,26 @@
package com.realnet.forma.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.forma.Entity.Child;
@Repository
public interface ChildRepository extends JpaRepository<Child, Integer> {
@Query(value = "select * from child where created_by=?1", nativeQuery = true)
List<Child> findAll(Long creayedBy);
@Query(value = "select * from child where created_by=?1", nativeQuery = true)
Page<Child> findAll(Pageable page, Long creayedBy);
}

View File

@ -0,0 +1,40 @@
package com.realnet.forma.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.forma.Entity.Testm;
@Repository
public interface TestmRepository extends JpaRepository<Testm, Integer> {
@Query(value = "select * from testm where created_by=?1", nativeQuery = true)
List<Testm> findAll(Long creayedBy);
@Query(value = "select * from testm where created_by=?1", nativeQuery = true)
Page<Testm> findAll(Pageable page, Long creayedBy);
}

View File

@ -0,0 +1,73 @@
package com.realnet.forma.Services;
import com.realnet.forma.Repository.ChildRepository;
import com.realnet.forma.Entity.Child
;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 ChildService {
@Autowired
private ChildRepository Repository;
@Autowired
private AppUserServiceImpl userService;
@Autowired
private RealmService realmService;
public Child Savedata(Child data) {
data.setUpdatedBy(getUser().getUserId());
data.setCreatedBy(getUser().getUserId());
data.setAccountId(getUser().getAccount().getAccount_id());
Child save = Repository.save(data);
return save;
}
// get all with pagination
public Page<Child> getAllWithPagination(Pageable page) {
return Repository.findAll(page, getUser().getUserId());
}
public List<Child> getdetails() {
List<Realm> realm = realmService.findByUserId(getUser().getUserId());
List<Child> all = Repository.findAll(getUser().getUserId());
return all ; }
public Child getdetailsbyId(Integer id) {
return Repository.findById(id).get();
}
public void delete_by_id(Integer id) {
Repository.deleteById(id);
}
public Child update(Child data,Integer id) {
Child old = Repository.findById(id).get();
old.setNamemmm(data.getNamemmm());
final Child test = Repository.save(old);
data.setUpdatedBy(getUser().getUserId());
return test;}
public AppUser getUser() {
AppUser user = userService.getLoggedInUser();
return user;
}}

View File

@ -0,0 +1,152 @@
package com.realnet.forma.Services;
import com.realnet.forma.Repository.TestmRepository;
import com.realnet.forma.Entity.Testm
;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 TestmService {
@Autowired
private TestmRepository Repository;
@Autowired
private AppUserServiceImpl userService;
@Autowired
private RealmService realmService;
public Testm Savedata(Testm data) {
data.setUpdatedBy(getUser().getUserId());
data.setCreatedBy(getUser().getUserId());
data.setAccountId(getUser().getAccount().getAccount_id());
Testm save = Repository.save(data);
return save;
}
// get all with pagination
public Page<Testm> getAllWithPagination(Pageable page) {
return Repository.findAll(page, getUser().getUserId());
}
public List<Testm> getdetails() {
List<Realm> realm = realmService.findByUserId(getUser().getUserId());
List<Testm> all = Repository.findAll(getUser().getUserId());
return all ; }
public Testm getdetailsbyId(Integer id) {
return Repository.findById(id).get();
}
public void delete_by_id(Integer id) {
Repository.deleteById(id);
}
public Testm update(Testm data,Integer id) {
Testm old = Repository.findById(id).get();
old.setNamem(data.getNamem());
old.setBar_code(data.getBar_code());
old.setQr_code(data.getQr_code());
old.setChild(data.getChild());
old.setNumberm(data.getNumberm());
old.setNumberb(data.getNumberb());
old.setCalculatedgg(data.getCalculatedgg());
final Testm test = Repository.save(old);
data.setUpdatedBy(getUser().getUserId());
return test;}
public AppUser getUser() {
AppUser user = userService.getLoggedInUser();
return user;
}}

View File

@ -0,0 +1,47 @@
package com.realnet.forma.Services;
import java.util.*;
import com.realnet.forma.Repository.TestmRepository;
import com.realnet.forma.Entity.Testm;
import com.realnet.forma.Entity.Testm_ListFilter1;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Testm_ListFilter1Service {
@Autowired
private TestmRepository Repository;
public List<Testm_ListFilter1> getlistbuilder() {
List<Testm> list= Repository.findAll();
ArrayList<Testm_ListFilter1> l = new ArrayList<>();
for (Testm data : list) {
{
Testm_ListFilter1 dummy = new Testm_ListFilter1();
dummy.setId(data.getId());
dummy.setNamem(data.getNamem());
l.add(dummy);
}
}
return l;}
public List<Testm_ListFilter1> getlistbuilderparam( ) {
List<Testm> list= Repository.findAll();
ArrayList<Testm_ListFilter1> l = new ArrayList<>();
for (Testm data : list) {
{
Testm_ListFilter1 dummy = new Testm_ListFilter1();
dummy.setId(data.getId());
dummy.setNamem(data.getNamem());
l.add(dummy);
}
}
return l;}
}

View File

@ -0,0 +1,4 @@
CREATE TABLE db.Testm(id BIGINT NOT NULL AUTO_INCREMENT, calculatedgg VARCHAR(400), onetoone VARCHAR(400), numberb int, valuell VARCHAR(400), bar_code VARCHAR(400), qr_code VARCHAR(400), namem VARCHAR(400), datagg VARCHAR(400), numberm int, PRIMARY KEY (id));
CREATE TABLE db.Child(id BIGINT NOT NULL AUTO_INCREMENT, namemmm VARCHAR(400), PRIMARY KEY (id));

View File

@ -0,0 +1,76 @@
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 childApiService {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<List<Map<String, dynamic>>> getEntities() async {
try {
final response = await _helper.getGetApiResponse('$baseUrl/Child/Child');
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/Child/Child/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/Child/Child', 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/Child/Child/$entityId',
entity); print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity( int entityId) async {
try {
await _helper.getDeleteApiResponse('$baseUrl/Child/Child/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
}

View File

@ -0,0 +1,152 @@
// 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 '../Child_viewModel/Child_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 childCreateEntityScreen extends StatefulWidget {
const childCreateEntityScreen({super.key});
@override
_childCreateEntityScreenState createState() => _childCreateEntityScreenState();
}
class _childCreateEntityScreenState extends State<childCreateEntityScreen> {
final Map<String, dynamic> formData = {};
final _formKey = GlobalKey<FormState>();
final TextEditingController namemmmController = TextEditingController();
@override
void initState() {
super.initState();
final provider = Provider.of<ChildViewModelScreen>(context, listen: false);
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<ChildViewModelScreen>(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 Child"),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
ReusableTextField(
controller: namemmmController,
onSaved:(value) => formData['namemmm'] = value ,
label:"Enter Namemmm",
// 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();
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 Child: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
},
),
],
),
),
),
),
);
}
}

View File

@ -0,0 +1,578 @@
// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'Child_create_entity_screen.dart';
import 'Child_update_entity_screen.dart';
import '../Child_viewModel/Child_view_model_screen.dart';
import 'package:flutter/services.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import '../../../../theme/app_style.dart';
import '../../../../utils/size_utils.dart';
import '../../../../widgets/custom_icon_button.dart';
import '../../../../utils/image_constant.dart';
import '../../../../widgets/app_bar/appbar_image.dart';
import '../../../../widgets/app_bar/appbar_title.dart';
import '../../../../widgets/app_bar/custom_app_bar.dart';
import '../../../../theme/app_decoration.dart';
import 'package:multi_select_flutter/multi_select_flutter.dart';
import '../../../../Reuseable/reusable_text_field.dart';
import 'package:provider/provider.dart';
import 'package:fluttertoast/fluttertoast.dart';
class child_entity_list_screen extends StatefulWidget {
final Map<String, dynamic> tabEntity;
const child_entity_list_screen({required this.tabEntity, Key? key})
: super(key: key); static const String routeName = '/entity-list';
@override
_child_entity_list_screenState createState() => _child_entity_list_screenState();
}
class _child_entity_list_screenState extends State<child_entity_list_screen> {
List<Map<String, dynamic>> entities = [];
List<Map<String, dynamic>> filteredEntities = [];
List<Map<String, dynamic>> serachEntities = [];
bool showCardView = true; // Add this variable to control the view mode
TextEditingController searchController = TextEditingController();
late stt.SpeechToText _speech;
bool isLoading = false; // Add this variable to track loading state
int currentPage = 0;
int pageSize = 10; // Adjust this based on your backend API
final ScrollController _scrollController = ScrollController();
@override
void initState() {
_speech = stt.SpeechToText();
super.initState();
fetchEntities();
_scrollController.addListener(_scrollListener);
fetchwithoutpaging();
}
Future<void> fetchwithoutpaging() async {
try {
final provider =
Provider.of<ChildViewModelScreen>(context, listen: false);
final fetchedEntities = await provider.getEntities();
print('withoutpaging data is $fetchedEntities');
setState(() {
serachEntities = fetchedEntities; // Update only filteredEntities
});
print('Child entity is .. $serachEntities');
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('Failed to fetch Child: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
Future<void> fetchEntities() async {
try {
setState(() {
isLoading = true;
});
final provider =
Provider.of<ChildViewModelScreen>(context, listen: false);
final fetchedEntities = await provider.getEntities(widget.tabEntity['id']);
setState(() {
var getentity = widget.tabEntity['gauravt2'];
final fetchedEntities =
(getentity as List).cast<Map<String, dynamic>>();
entities.addAll(fetchedEntities); // Add new data to the existing list
filteredEntities = entities.toList(); // Update only filteredEntities
serachEntities = filteredEntities;
currentPage++;
});
print(' entity is .. $filteredEntities');
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('Failed to fetch Child data: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
} finally {
setState(() {
isLoading = false;
});
}
}
void _scrollListener() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
fetchEntities();
}
}
Future<void> deleteEntity(Map<String, dynamic> entity) async {
try {
final provider =
Provider.of<ChildViewModelScreen>(context, listen: false);
await provider.deleteEntity(entity['id']);;
setState(() {
entities.remove(entity);
});
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('Failed to delete entity: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
void _searchEntities(String keyword) {
setState(() {
filteredEntities = serachEntities
.where((entity) =>
entity['namemmm'].toString().toLowerCase().contains(keyword.toLowerCase())
).toList();
});
}
void _startListening() async {
if (!_speech.isListening) {
bool available = await _speech.initialize(
onStatus: (status) {
print('Speech recognition status: $status');
},
onError: (error) {
print('Speech recognition error: $error');
},
);
if (available) {
_speech.listen(
onResult: (result) {
if (result.finalResult) {
searchController.text = result.recognizedWords;
_searchEntities(result.recognizedWords);
}
},
);
}
}
}
void _stopListening() {
if (_speech.isListening) {
_speech.stop();
}
}
@override
void dispose() {
_speech.cancel();
super.dispose();
}
onTapArrowleft1(BuildContext context) {
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: CustomAppBar(
height: getVerticalSize(49),
leadingWidth: 40,
leading: AppbarImage(
height: getSize(24),
width: getSize(24),
svgPath: ImageConstant.imgArrowleft,
margin: getMargin(left: 16, top: 12, bottom: 13),
onTap: () {
onTapArrowleft1(context);
}),
centerTitle: true,
title: AppbarTitle(text: " Child"),
actions: [
Row(
children: [
Switch(
activeColor: Colors.greenAccent,
inactiveThumbColor: Colors.white,
value: showCardView,
onChanged: (value) {
setState(() {
showCardView = value;
});
},
),
],
), ],
),
body: RefreshIndicator(
onRefresh: () async {
currentPage = 1;
entities.clear();
await fetchEntities();
},
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: searchController,
onChanged: (value) {
_searchEntities(value);
},
decoration: InputDecoration(
hintText: 'Search...',
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
filled: true,
fillColor: Colors.grey[200],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide.none,
),
suffixIcon: IconButton(
icon: const Icon(Icons.mic),
onPressed: () {
_startListening();
},
),
),
),
),
Expanded(
child: ListView.builder(
itemCount: filteredEntities.length + (isLoading ? 1 : 0),
itemBuilder: (BuildContext context, int index) {
if (index < filteredEntities.length) {
final entity = filteredEntities[index];
return _buildListItem(entity);
} else {
// Display the loading indicator at the bottom when new data is loading
return const Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child: CircularProgressIndicator(),
),
);
}
},
controller: _scrollController,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => ChildViewModelScreen(),
child: childCreateEntityScreen(),
),
),
).then((_) {
fetchEntities();
});
},
child: const Icon(Icons.add),
),
));
}
Widget _buildListItem(Map<String, dynamic> entity) {
return showCardView ? _buildCardView(entity) : _buildNormalView(entity);
}
// Function to build card view for a list item
Widget _buildCardView(Map<String, dynamic> entity) {
return Card(
elevation: 2,
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: _buildNormalView(entity))
; }
// Function to build normal view for a list item
// Function to build normal view for a list item
Widget _buildNormalView(Map<String, dynamic> entity) {
final values = entity.values.elementAt(21) ?? 'Authsec';
return SizedBox(
width: double.maxFinite,
child: Container(
padding: getPadding(
left: 16,
top: 5,
right: 5,
bottom: 17,
),
decoration: AppDecoration.outlineGray70011.copyWith(
borderRadius: BorderRadiusStyle.roundedBorder6,
color: Colors.grey[100]),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: getPadding(
//right: 13,
),
child: Row(
children: [
Container(
width: MediaQuery.of(context).size.width * 0.30,
margin: getMargin(
left: 8,
top: 3,
bottom: 1,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
entity['id'].toString(),
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGreenSemiBold16,
),
],
),
),
const Spacer(),
PopupMenuButton<String>(
icon: const Icon(
Icons.more_vert,
color: Colors.black,
size: 16,
),
itemBuilder: (BuildContext context) {
return [
PopupMenuItem<String>(
value: 'edit',
child: Row(
children: [
const Icon(
Icons.edit,
size: 16, // Adjust the icon size as needed
),
const SizedBox(width: 8),
Text(
'Edit',
style: AppStyle
.txtGilroySemiBold16, // Adjust the text size as needed
),
],
),
),
PopupMenuItem<String>(
value: 'delete',
child: Row(
children: [
const Icon(
Icons.delete,
size: 16, // Adjust the icon size as needed
),
const SizedBox(width: 8),
Text(
'Delete',
style: AppStyle
.txtGilroySemiBold16, // Adjust the text size as needed
),
],
),
),
];
},
onSelected: (String value) {
if (value == 'edit') {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => ChildViewModelScreen(),
child: childUpdateEntityScreen(entity: entity),
),
),
).then((_) {
fetchEntities();
});
} else if (value == 'delete') {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Confirm Deletion'),
content: const Text(
'Are you sure you want to delete?'),
actions: [
TextButton(
child: const Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: const Text('Delete'),
onPressed: () {
Navigator.of(context).pop();
deleteEntity(entity)
.then((value) => {fetchEntities()});
},
),
],
);
},
);
}
},
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Namemmm : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['namemmm'].toString() ?? 'No Namemmm Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
],
),
),
);
}
Widget _buildLeadingIcon(String title) {
return CircleAvatar(
backgroundColor: Colors.blue,
child: Text(
title.isNotEmpty ? title[0].toUpperCase() : 'NA',
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
);
}
void _showAdditionalFieldsDialog(
BuildContext context,
Map<String, dynamic> entity,
) {
final dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Additional Fields'),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Created At: ${_formatTimestamp(entity['createdAt'], dateFormat)}'),
Text('Created By: ${entity['createdBy'] ?? 'N/A'}'),
Text('Updated By: ${entity['updatedBy'] ?? 'N/A'}'),
Text(
'Updated At: ${_formatTimestamp(entity['updatedAt'], dateFormat)}'),
Text('Account ID: ${entity['accountId'] ?? 'N/A'}'),
],
),
actions: [
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
String _formatTimestamp(dynamic timestamp, DateFormat dateFormat) {
if (timestamp is int) {
final DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
return dateFormat.format(dateTime);
} else if (timestamp is String) {
return timestamp;
} else {
return 'N/A';
}
}
}

View File

@ -0,0 +1,143 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Child_viewModel/Child_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 childUpdateEntityScreen extends StatefulWidget {
final Map<String, dynamic> entity;
childUpdateEntityScreen({required this.entity});
@override
_childUpdateEntityScreenState createState() => _childUpdateEntityScreenState();
}
class _childUpdateEntityScreenState extends State<childUpdateEntityScreen> {
final _formKey = GlobalKey<FormState>();
@override
void initState() {
super.initState();
final provider = Provider.of<ChildViewModelScreen>(context, listen: false);
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<ChildViewModelScreen>(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 Child"), actions: [
],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
ReusableTextField(
label: "Please Enter Namemmm",
initialValue: widget.entity['namemmm'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['namemmm'] = 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();
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 Child: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
},
),
],
),
),
),
),
);
}
}

View File

@ -0,0 +1,64 @@
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 ChildRepoScreen {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<dynamic> getEntities() async {
try {
final response =
await _helper.getGetApiResponse('$baseUrl/Child/Child');
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/Child/Child/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/Child/Child', 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/Child/Child/$entityId', entity);
print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity(int entityId) async {
try {
await _helper
.getDeleteApiResponse('$baseUrl/Child/Child/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
}

View File

@ -0,0 +1,103 @@
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 '../Child_Repo/Child_repo_screen.dart';
class ChildViewModelScreen extends ChangeNotifier{
final ChildRepoScreen repo = ChildRepoScreen();
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

@ -0,0 +1,104 @@
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 testmApiService {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<List<Map<String, dynamic>>> getEntities() async {
try {
final response = await _helper.getGetApiResponse('$baseUrl/Testm/Testm');
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/Testm/Testm/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/Testm/Testm', 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/Testm/Testm/$entityId',
entity); print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity( int entityId) async {
try {
await _helper.getDeleteApiResponse('$baseUrl/Testm/Testm/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
}

View File

@ -0,0 +1,687 @@
// 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 '../Testm_viewModel/Testm_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 testmCreateEntityScreen extends StatefulWidget {
const testmCreateEntityScreen({super.key});
@override
_testmCreateEntityScreenState createState() => _testmCreateEntityScreenState();
}
class _testmCreateEntityScreenState extends State<testmCreateEntityScreen> {
final Map<String, dynamic> formData = {};
final _formKey = GlobalKey<FormState>();
final TextEditingController namemController = TextEditingController();
final TextEditingController fieldggController = TextEditingController();
Widget buildFormField(String fieldOption) {
return Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: TextFormField(
decoration: InputDecoration(
labelText: fieldOption,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
onSaved: (value) {
if (formData['child'] == null) {
formData['child'] = {};
}
formData['child'][fieldOption] = value;
},
),
),
),
);
}
late Future<List<Map<String, dynamic>>> _dataggdataFuture; // Data from fetchData
Future<List<Map<String, dynamic>>> dataggfetchData() async {
final provider =
Provider.of<TestmViewModelScreen>(context, listen: false);
final resp = await provider.getdataggGrid();
if (resp != null) {
return resp;
} else {
throw Exception('Failed to load data: ');
}
}
late Future<List<Map<String, dynamic>>> _valuelldataFuture; // Data from fetchData
Future<List<Map<String, dynamic>>> valuellfetchData() async {
final resp = await apiService.getEntities();
if (resp != null) {
return resp;
} else {
throw Exception('Failed to load data: ');
}
}
void showvaluellDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return SingleChildScrollView(
child: AlertDialog(
title: const Text('Select a record'),
content: FutureBuilder<List<Map<String, dynamic>>>(
future: _valuelldataFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No data available..'));
} else {
final List<String> columnsToShow = [
'namem',
];
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columnSpacing: 30,
headingRowColor: MaterialStateColor.resolveWith(
(states) => Colors.blue.shade100),
dataRowColor: MaterialStateColor.resolveWith(
(states) => Colors.white),
dividerThickness: 0.5,
columns: columnsToShow
.map(
(key) => DataColumn(
label: Text(
key,
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 16),
),
),
)
.toList(),
rows: snapshot.data!.map((item) {
return DataRow(
cells: columnsToShow.map((key) {
return DataCell(
Text(
item[key].toString(),
style: const TextStyle(fontSize: 14),
),
onTap: () {
setState(() {
namemController.text = item['namem'] ?? '';
// Add more fields as needed
});
Navigator.pop(context);
},
);
}).toList());
}).toList(),
),
);
}
},
),
actions: [
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
},
);
}
final TextEditingController numbermController = TextEditingController();
final TextEditingController numberbController = TextEditingController();
String calculatedggOperator = '+';
String calculatedggresult = '';
final List<String> calculatedggoperators = ['+', '-', '*', '/'];
void calculatecalculatedggResult() {
int calculation;
switch (calculatedggOperator) {
case '+':
calculation =
int.parse(numbermController.text) +
int.parse(numberbController.text) +
0;
break;
case '-':
calculation =
int.parse(numbermController.text) -
int.parse(numberbController.text) -
0;
break;
case '*':
calculation =
int.parse(numbermController.text) *
int.parse(numberbController.text) *
1;
break;
case '/':
if (
int.parse(numbermController.text)== 0 ||
int.parse(numberbController.text)== 0 ||
1 != 1) {
calculatedggresult = 'Division by zero error';
return;
}
calculation = (
int.parse(numbermController.text) /
int.parse(numberbController.text) /
1).toInt();
break;
default:
calculation = 0;
}
setState(() {
calculatedggresult = 'Result: $calculation';
});
}
@override
void initState() {
super.initState();
final provider = Provider.of<TestmViewModelScreen>(context, listen: false);
_dataggdataFuture = dataggfetchData(); // Initialize _dataFuture with the function
_valuelldataFuture = valuellfetchData(); // Initialize _dataFuture with the function
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<TestmViewModelScreen>(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 Testm"),
actions: [
IconButton(
icon: const Icon(Icons.grid_on),
onPressed: () {
showvaluellDialog(context);
},
),
],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
ReusableTextField(
controller: namemController,
onSaved:(value) => formData['namem'] = value ,
label:"Enter Namem",
// ValidationProperties
),
SizedBox(height: 16),
Container(
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8.0),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
spreadRadius: 2,
blurRadius: 4,
offset: Offset(0, 2),
),
],
),
child: Column(
children: [
Text(
"Fieldgg",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 16),
ReusableTextField(
onSaved:(value) => formData['bar_code'] = value ,
label:"Enter Bar_code",
// ValidationProperties
),
SizedBox(height: 16),
ReusableTextField(
onSaved:(value) => formData['qr_code'] = value ,
label:"Enter Qr_code",
// ValidationProperties
),
SizedBox(height: 16),
SizedBox(height: 16),
],
),
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 20,
child: Text(
'Child',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
const SizedBox(height: 16), // Add space between elements
buildFormField('namemmm'),
],
),
),
ReusableTextField(
controller: numbermController,
onSaved:(value) => formData['numberm'] = value ,
label: "Enter Numberm",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
// ValidationProperties
),
SizedBox(height: 16),
ReusableTextField(
controller: numberbController,
onSaved:(value) => formData['numberb'] = value ,
label: "Enter Numberb",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
// ValidationProperties
),
SizedBox(height: 16),
const SizedBox(height: 8.0),
DropdownButtonFormField<String>(
value: calculatedggOperator,
items: calculatedggoperators.map((String operator) {
return DropdownMenuItem(
value: operator,
child: Text(operator),
);
}).toList(),
onChanged: (value) {
setState(() {
calculatedggOperator = value!;
print(calculatedggOperator.toString());
print("value-- $value");
});
},
decoration: const InputDecoration(labelText: 'Operator'),
),
const SizedBox(height: 20.0),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState?.save(); // Save the form fields
}
calculatecalculatedggResult();
setState(() {
});
},
child: const Text('Calculate'),
),
const SizedBox(height: 20.0),
Text(calculatedggresult,style: TextStyle(color: Colors.black),),
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();
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 Testm: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
},
),
SizedBox(height: 16),
FutureBuilder<List<Map<String, dynamic>>>(
future: _dataggdataFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No data available..'));
} else {
final keys = snapshot.data!.first.keys.toList();
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columnSpacing: 30,
headingRowColor: MaterialStateColor.resolveWith((states) => Colors.blue.shade100),
dataRowColor: MaterialStateColor.resolveWith((states) => Colors.white),
dividerThickness: 0.5,
columns: keys.map(
(key) => DataColumn(
label: Text(
key,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
),
)
.toList(),
rows: snapshot.data!.map((item) {
return DataRow(cells: keys.map((key) {
return DataCell(
Text(
item[key].toString(),
style: const TextStyle(fontSize: 14),
),
);
}).toList());
}).toList(),
),
);
}
},
),
SizedBox(height: 16),
],
),
),
),
),
);
}
}

View File

@ -0,0 +1,760 @@
// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'Testm_create_entity_screen.dart';
import 'Testm_update_entity_screen.dart';
import '../Testm_viewModel/Testm_view_model_screen.dart';
import 'package:flutter/services.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import '../../../../theme/app_style.dart';
import '../../../../utils/size_utils.dart';
import '../../../../widgets/custom_icon_button.dart';
import '../../../../utils/image_constant.dart';
import '../../../../widgets/app_bar/appbar_image.dart';
import '../../../../widgets/app_bar/appbar_title.dart';
import '../../../../widgets/app_bar/custom_app_bar.dart';
import '../../../../theme/app_decoration.dart';
import 'package:multi_select_flutter/multi_select_flutter.dart';
import '../../../../Reuseable/reusable_text_field.dart';
import 'package:provider/provider.dart';
import 'package:fluttertoast/fluttertoast.dart';
class testm_entity_list_screen extends StatefulWidget {
static const String routeName = '/entity-list';
@override
_testm_entity_list_screenState createState() => _testm_entity_list_screenState();
}
class _testm_entity_list_screenState extends State<testm_entity_list_screen> {
List<Map<String, dynamic>> entities = [];
List<Map<String, dynamic>> filteredEntities = [];
List<Map<String, dynamic>> serachEntities = [];
bool showCardView = true; // Add this variable to control the view mode
TextEditingController searchController = TextEditingController();
late stt.SpeechToText _speech;
bool isLoading = false; // Add this variable to track loading state
int currentPage = 0;
int pageSize = 10; // Adjust this based on your backend API
final ScrollController _scrollController = ScrollController();
@override
void initState() {
_speech = stt.SpeechToText();
super.initState();
fetchEntities();
_scrollController.addListener(_scrollListener);
fetchwithoutpaging();
}
Future<void> fetchwithoutpaging() async {
try {
final provider =
Provider.of<TestmViewModelScreen>(context, listen: false);
final fetchedEntities = await provider.getEntities();
print('withoutpaging data is $fetchedEntities');
setState(() {
serachEntities = fetchedEntities; // Update only filteredEntities
});
print('Testm entity is .. $serachEntities');
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('Failed to fetch Testm: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
Future<void> fetchEntities() async {
try {
setState(() {
isLoading = true;
});
final provider =
Provider.of<TestmViewModelScreen>(context, listen: false);
final fetchedEntities =
await provider.getAllWithPagination(currentPage, pageSize);
print('pagination data is $fetchedEntities');
setState(() {
entities.addAll(fetchedEntities); // Add new data to the existing list
filteredEntities = entities.toList(); // Update only filteredEntities
currentPage++;
});
print(' entity is .. $filteredEntities');
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('Failed to fetch Testm data: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
} finally {
setState(() {
isLoading = false;
});
}
}
void _scrollListener() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
fetchEntities();
}
}
Future<void> deleteEntity(Map<String, dynamic> entity) async {
try {
final provider =
Provider.of<TestmViewModelScreen>(context, listen: false);
await provider.deleteEntity(entity['id']);;
setState(() {
entities.remove(entity);
});
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('Failed to delete entity: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
void _searchEntities(String keyword) {
setState(() {
filteredEntities = serachEntities
.where((entity) =>
entity['namem'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['bar_code'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['qr_code'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['child'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['datagg'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['numberm'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['numberb'].toString().toLowerCase().contains(keyword.toLowerCase())
).toList();
});
}
void _startListening() async {
if (!_speech.isListening) {
bool available = await _speech.initialize(
onStatus: (status) {
print('Speech recognition status: $status');
},
onError: (error) {
print('Speech recognition error: $error');
},
);
if (available) {
_speech.listen(
onResult: (result) {
if (result.finalResult) {
searchController.text = result.recognizedWords;
_searchEntities(result.recognizedWords);
}
},
);
}
}
}
void _stopListening() {
if (_speech.isListening) {
_speech.stop();
}
}
@override
void dispose() {
_speech.cancel();
super.dispose();
}
onTapArrowleft1(BuildContext context) {
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: CustomAppBar(
height: getVerticalSize(49),
leadingWidth: 40,
leading: AppbarImage(
height: getSize(24),
width: getSize(24),
svgPath: ImageConstant.imgArrowleft,
margin: getMargin(left: 16, top: 12, bottom: 13),
onTap: () {
onTapArrowleft1(context);
}),
centerTitle: true,
title: AppbarTitle(text: " Testm"),
actions: [
Row(
children: [
Switch(
activeColor: Colors.greenAccent,
inactiveThumbColor: Colors.white,
value: showCardView,
onChanged: (value) {
setState(() {
showCardView = value;
});
},
),
],
), ],
),
body: RefreshIndicator(
onRefresh: () async {
currentPage = 1;
entities.clear();
await fetchEntities();
},
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: searchController,
onChanged: (value) {
_searchEntities(value);
},
decoration: InputDecoration(
hintText: 'Search...',
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
filled: true,
fillColor: Colors.grey[200],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide.none,
),
suffixIcon: IconButton(
icon: const Icon(Icons.mic),
onPressed: () {
_startListening();
},
),
),
),
),
Expanded(
child: ListView.builder(
itemCount: filteredEntities.length + (isLoading ? 1 : 0),
itemBuilder: (BuildContext context, int index) {
if (index < filteredEntities.length) {
final entity = filteredEntities[index];
return _buildListItem(entity);
} else {
// Display the loading indicator at the bottom when new data is loading
return const Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child: CircularProgressIndicator(),
),
);
}
},
controller: _scrollController,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => TestmViewModelScreen(),
child: testmCreateEntityScreen(),
),
),
).then((_) {
fetchEntities();
});
},
child: const Icon(Icons.add),
),
));
}
Widget _buildListItem(Map<String, dynamic> entity) {
return showCardView ? _buildCardView(entity) : _buildNormalView(entity);
}
// Function to build card view for a list item
Widget _buildCardView(Map<String, dynamic> entity) {
return Card(
elevation: 2,
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: _buildNormalView(entity))
; }
// Function to build normal view for a list item
// Function to build normal view for a list item
Widget _buildNormalView(Map<String, dynamic> entity) {
final values = entity.values.elementAt(21) ?? 'Authsec';
return SizedBox(
width: double.maxFinite,
child: Container(
padding: getPadding(
left: 16,
top: 5,
right: 5,
bottom: 17,
),
decoration: AppDecoration.outlineGray70011.copyWith(
borderRadius: BorderRadiusStyle.roundedBorder6,
color: Colors.grey[100]),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: getPadding(
//right: 13,
),
child: Row(
children: [
Container(
width: MediaQuery.of(context).size.width * 0.30,
margin: getMargin(
left: 8,
top: 3,
bottom: 1,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
entity['id'].toString(),
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGreenSemiBold16,
),
],
),
),
const Spacer(),
PopupMenuButton<String>(
icon: const Icon(
Icons.more_vert,
color: Colors.black,
size: 16,
),
itemBuilder: (BuildContext context) {
return [
PopupMenuItem<String>(
value: 'edit',
child: Row(
children: [
const Icon(
Icons.edit,
size: 16, // Adjust the icon size as needed
),
const SizedBox(width: 8),
Text(
'Edit',
style: AppStyle
.txtGilroySemiBold16, // Adjust the text size as needed
),
],
),
),
PopupMenuItem<String>(
value: 'delete',
child: Row(
children: [
const Icon(
Icons.delete,
size: 16, // Adjust the icon size as needed
),
const SizedBox(width: 8),
Text(
'Delete',
style: AppStyle
.txtGilroySemiBold16, // Adjust the text size as needed
),
],
),
),
];
},
onSelected: (String value) {
if (value == 'edit') {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => TestmViewModelScreen(),
child: testmUpdateEntityScreen(entity: entity),
),
),
).then((_) {
fetchEntities();
});
} else if (value == 'delete') {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Confirm Deletion'),
content: const Text(
'Are you sure you want to delete?'),
actions: [
TextButton(
child: const Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: const Text('Delete'),
onPressed: () {
Navigator.of(context).pop();
deleteEntity(entity)
.then((value) => {fetchEntities()});
},
),
],
);
},
);
}
},
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Namem : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['namem'].toString() ?? 'No Namem Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Bar_code : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['bar_code'].toString() ?? 'No Bar_code Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Qr_code : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['qr_code'].toString() ?? 'No Qr_code Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Numberm : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['numberm'].toString() ?? 'No Numberm Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Numberb : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['numberb'].toString() ?? 'No Numberb Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
],
),
),
);
}
Widget _buildLeadingIcon(String title) {
return CircleAvatar(
backgroundColor: Colors.blue,
child: Text(
title.isNotEmpty ? title[0].toUpperCase() : 'NA',
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
);
}
void _showAdditionalFieldsDialog(
BuildContext context,
Map<String, dynamic> entity,
) {
final dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Additional Fields'),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Created At: ${_formatTimestamp(entity['createdAt'], dateFormat)}'),
Text('Created By: ${entity['createdBy'] ?? 'N/A'}'),
Text('Updated By: ${entity['updatedBy'] ?? 'N/A'}'),
Text(
'Updated At: ${_formatTimestamp(entity['updatedAt'], dateFormat)}'),
Text('Account ID: ${entity['accountId'] ?? 'N/A'}'),
],
),
actions: [
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
String _formatTimestamp(dynamic timestamp, DateFormat dateFormat) {
if (timestamp is int) {
final DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
return dateFormat.format(dateTime);
} else if (timestamp is String) {
return timestamp;
} else {
return 'N/A';
}
}
}

View File

@ -0,0 +1,393 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Testm_viewModel/Testm_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 testmUpdateEntityScreen extends StatefulWidget {
final Map<String, dynamic> entity;
testmUpdateEntityScreen({required this.entity});
@override
_testmUpdateEntityScreenState createState() => _testmUpdateEntityScreenState();
}
class _testmUpdateEntityScreenState extends State<testmUpdateEntityScreen> {
final _formKey = GlobalKey<FormState>();
Widget buildFormField(String fieldOption) {
return Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: TextFormField(
initialValue: widget.entity['child'] != null &&
widget.entity['child'][fieldOption] != null
? widget.entity['child'][fieldOption]
: '',
decoration: InputDecoration(
labelText: fieldOption,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
onSaved: (value) {
if (widget.entity['child'] == null) {
widget.entity['child'] = {};
}
widget.entity['child'][fieldOption] = value;
},
),
),
),
);
}
@override
void initState() {
super.initState();
final provider = Provider.of<TestmViewModelScreen>(context, listen: false);
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<TestmViewModelScreen>(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 Testm"), actions: [
],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
ReusableTextField(
label: "Please Enter Namem",
initialValue: widget.entity['namem'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['namem'] = value,
),
SizedBox(height: 16),
Container(
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8.0),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
spreadRadius: 2,
blurRadius: 4,
offset: Offset(0, 2),
),
],
),
child: Column(
children: [
Text(
"Fieldgg",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 16),
SizedBox(height: 16),
TextFormField(
initialValue: widget.entity['bar_code'],
decoration: InputDecoration(
labelText: 'fieldgg bar_code',
),
onChanged: (value) {
setState(() {
widget.entity['bar_code'] = value;
});
},
),
SizedBox(height: 16),
TextFormField(
initialValue: widget.entity['qr_code'],
decoration: InputDecoration(
labelText: 'fieldgg qr_code',
),
onChanged: (value) {
setState(() {
widget.entity['qr_code'] = value;
});
},
),
SizedBox(height: 16),
],
),
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 20,
child: Text(
'Child',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
const SizedBox(height: 16), // Add space between elements
buildFormField('namemmm'),
],
),
),
Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ElevatedButton(
onPressed: () {
// Save changes logic here
Navigator.pop(context);
// Implement API call to update data
},
child: Text('Save'),
),
],
),
),
ReusableTextField(
initialValue: widget.entity['numberm'].toString(),
onSaved: (value) => widget.entity['numberm']= value,
label: "Enter Numberm",
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['numberb'].toString(),
onSaved: (value) => widget.entity['numberb']= value,
label: "Enter Numberb",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a number';
}
return null;
},
),
CustomButton(
height: getVerticalSize(50),
text: "Update",
margin: getMargin(top: 24, bottom: 5),
onTap: () async {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
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 Testm: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
},
),
],
),
),
),
),
);
}
}

View File

@ -0,0 +1,86 @@
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 TestmRepoScreen {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<dynamic> getEntities() async {
try {
final response =
await _helper.getGetApiResponse('$baseUrl/Testm/Testm');
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/Testm/Testm/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/Testm/Testm', 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/Testm/Testm/$entityId', entity);
print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity(int entityId) async {
try {
await _helper
.getDeleteApiResponse('$baseUrl/Testm/Testm/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
Future<dynamic> getdataggGrid() async {
try {
String apiUrl = "$baseUrl/Testm_ListFilter1/Testm_ListFilter1";
final response = await _helper.getGetApiResponse(apiUrl);
return response;
} catch (e) {
throw Exception('Failed to Upload datagg: $e');
}
}
}

View File

@ -0,0 +1,132 @@
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 '../Testm_Repo/Testm_repo_screen.dart';
class TestmViewModelScreen extends ChangeNotifier{
final TestmRepoScreen repo = TestmRepoScreen();
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');
}
}
late List<Map<String, dynamic>> dataggdataFuture =
[]; // Data from fetchData
Future<List<Map<String, dynamic>>> getdataggGrid() async {
try {
final value = await repo.getdataggGrid();
dataggdataFuture = (value as List)
.map((item) => item as Map<String, dynamic>)
.toList();
return dataggdataFuture;
} catch (e) {
throw Exception('Failed to get all: $e');
}
}
}

View File

@ -1,3 +1,6 @@
import '../../Entity/forma/Testm/TestmView/Testm_entity_list_screen.dart';
import '../../Entity/forma/Testm/Testm_viewModel/Testm_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: 'Testm',
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => TestmViewModelScreen(),
child: testm_entity_list_screen(),
),
),
);
},
),
],
),
);
}
DrawerItem(
icon: Icons.logout,
color: Colors.red,
title: 'Logout',
onTap: () async {
await UserManager().clearUser();
Navigator.pushReplacementNamed(context, RouteNames.splashView);
},
),
],
),
);
}
}