build_app

This commit is contained in:
risadmin_prod 2025-03-29 04:34:12 +00:00
parent 5d16182a09
commit 03a7a0fe97
13 changed files with 4102 additions and 68 deletions

View File

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

View File

@ -0,0 +1,179 @@
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.Testk;
import com.realnet.forma.Services.TestkService ;
@RequestMapping(value = "/Testk")
@CrossOrigin("*")
@RestController
public class TestkController {
@Autowired
private TestkService Service;
@Value("${projectPath}")
private String projectPath;
@PostMapping("/Testk")
public Testk Savedata(@RequestBody Testk data) {
Testk save = Service.Savedata(data) ;
System.out.println("data saved..." + save);
return save;
}
@PutMapping("/Testk/{id}")
public Testk update(@RequestBody Testk data,@PathVariable Integer id ) {
Testk update = Service.update(data,id);
System.out.println("data update..." + update);
return update;
}
// get all with pagination
@GetMapping("/Testk/getall/page")
public Page<Testk> getall(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "size", required = false) Integer size) {
Pageable paging = PageRequest.of(page, size);
Page<Testk> get = Service.getAllWithPagination(paging);
return get;
}
@GetMapping("/Testk")
public List<Testk> getdetails() {
List<Testk> get = Service.getdetails();
return get;
}
// get all without authentication
@GetMapping("/token/Testk")
public List<Testk> getallwioutsec() {
List<Testk> get = Service.getdetails();
return get;
}
@GetMapping("/Testk/{id}")
public Testk getdetailsbyId(@PathVariable Integer id ) {
Testk get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Testk/{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,89 @@
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 Testk extends Extension {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private int decimals;
private int percentages;
private String recaptchas;
private String documentss;
private String radios;
private boolean s;
private boolean r;
private boolean f;
private String fileuploadxname;
private String fileuploadxpath ;
private String imageuploadaname;
private String imageuploadapath ;
private String audiosname;
private String audiospath ;
private String videoxxname;
private String videoxxpath ;
private String currencyx;
private String qrcode;
private String barcodes;
}

View File

@ -0,0 +1,50 @@
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.Testk;
@Repository
public interface TestkRepository extends JpaRepository<Testk, Integer> {
@Query(value = "select * from testk where created_by=?1", nativeQuery = true)
List<Testk> findAll(Long creayedBy);
@Query(value = "select * from testk where created_by=?1", nativeQuery = true)
Page<Testk> findAll(Pageable page, Long creayedBy);
}

View File

@ -0,0 +1,208 @@
package com.realnet.forma.Services;
import com.realnet.forma.Repository.TestkRepository;
import com.realnet.forma.Entity.Testk
;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 TestkService {
@Autowired
private TestkRepository Repository;
@Autowired
private AppUserServiceImpl userService;
@Autowired
private RealmService realmService;
@Autowired
private SequenceService documentsssequenceService;
public Testk Savedata(Testk data) {
data.setDocumentss (documentsssequenceService.GenerateSequence("k"));
data.setUpdatedBy(getUser().getUserId());
data.setCreatedBy(getUser().getUserId());
data.setAccountId(getUser().getAccount().getAccount_id());
Testk save = Repository.save(data);
return save;
}
// get all with pagination
public Page<Testk> getAllWithPagination(Pageable page) {
return Repository.findAll(page, getUser().getUserId());
}
public List<Testk> getdetails() {
List<Realm> realm = realmService.findByUserId(getUser().getUserId());
List<Testk> all = Repository.findAll(getUser().getUserId());
return all ; }
public Testk getdetailsbyId(Integer id) {
return Repository.findById(id).get();
}
public void delete_by_id(Integer id) {
Repository.deleteById(id);
}
public Testk update(Testk data,Integer id) {
Testk old = Repository.findById(id).get();
old.setDecimals(data.getDecimals());
old.setPercentages(data.getPercentages());
old.setRecaptchas(data.getRecaptchas());
old.setDocumentss(data.getDocumentss());
old.setRadios(data.getRadios());
old.setS(data.isS());
old.setR(data.isR());
old.setF(data.isF());
old.setCurrencyx(data.getCurrencyx());
old.setQrcode(data.getQrcode());
old.setBarcodes(data.getBarcodes());
final Testk 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.Testk(id BIGINT NOT NULL AUTO_INCREMENT, fileuploadx VARCHAR(400), percentages int, currencyx VARCHAR(400), qrcode VARCHAR(400), f bit(1), videoxx VARCHAR(400), barcodes VARCHAR(400), radios VARCHAR(400), decimals int, r bit(1), s bit(1), documentss VARCHAR(400), recaptchas VARCHAR(400), audios VARCHAR(400), imageuploada VARCHAR(400), PRIMARY KEY (id));

View File

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

View File

@ -0,0 +1,912 @@
// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'Testk_create_entity_screen.dart';
import 'Testk_update_entity_screen.dart';
import '../Testk_viewModel/Testk_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 testk_entity_list_screen extends StatefulWidget {
static const String routeName = '/entity-list';
@override
_testk_entity_list_screenState createState() => _testk_entity_list_screenState();
}
class _testk_entity_list_screenState extends State<testk_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<TestkViewModelScreen>(context, listen: false);
final fetchedEntities = await provider.getEntities();
print('withoutpaging data is $fetchedEntities');
setState(() {
serachEntities = fetchedEntities; // Update only filteredEntities
});
print('Testk entity is .. $serachEntities');
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('Failed to fetch Testk: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
Future<void> fetchEntities() async {
try {
setState(() {
isLoading = true;
});
final provider =
Provider.of<TestkViewModelScreen>(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 Testk 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<TestkViewModelScreen>(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['decimals'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['percentages'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['documentss'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['radios'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['audios'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['videoxx'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['currencyx'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['qrcode'].toString().toLowerCase().contains(keyword.toLowerCase()) ||
entity['barcodes'].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: " Testk"),
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) => TestkViewModelScreen(),
child: testkCreateEntityScreen(),
),
),
).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) => TestkViewModelScreen(),
child: testkUpdateEntityScreen(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(
"Decimals : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['decimals'].toString() ?? 'No Decimals Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Percentages : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['percentages'].toString() ?? 'No Percentages Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"documentss : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['documentss'].toString() ?? 'No documentss Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Radios : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['radios'].toString() ?? 'No Radios Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"S : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['s'].toString() ?? 'No S Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"R : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['r'].toString() ?? 'No R Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"F : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['f'].toString() ?? 'No F Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Currencyx : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['currencyx'].toString() ?? 'No Currencyx Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Qrcode : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['qrcode'].toString() ?? 'No Qrcode Available',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16Bluegray900,
),
],
),
),
Padding(
padding: getPadding(
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Barcodes : ",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle.txtGilroyMedium16,
),
Text(
entity['barcodes'].toString() ?? 'No Barcodes 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,653 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Testk_viewModel/Testk_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 testkUpdateEntityScreen extends StatefulWidget {
final Map<String, dynamic> entity;
testkUpdateEntityScreen({required this.entity});
@override
_testkUpdateEntityScreenState createState() => _testkUpdateEntityScreenState();
}
class _testkUpdateEntityScreenState extends State<testkUpdateEntityScreen> {
final _formKey = GlobalKey<FormState>();
String? selectedradios;
Future<void> _showradiosSelectionDialog(BuildContext context) async {
final result = await showDialog<String>(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Select radios'),
children: [
RadioListTile<String>(
title: const Text('f'),
value: 'f',
groupValue: selectedradios,
onChanged: (value) {
setState(() {
selectedradios = value;
Navigator.pop(context, value);
});
},
),
RadioListTile<String>(
title: const Text('m'),
value: 'm',
groupValue: selectedradios,
onChanged: (value) {
setState(() {
selectedradios = value;
Navigator.pop(context, value);
});
},
),
],
);
},
);
if (result != null) {
setState(() {
selectedradios = result;
});
}
}
bool scBox = false;
bool rcBox = false;
bool fcBox = false;
final TextEditingController _inputcurrencyxController = TextEditingController();
double editedcurrencyxValue = 0.0;
late String inputDataqrcode;
late TextEditingController controllerInputqrcode;
late String inputDatabarcodes; // By default barcode
TextEditingController controllerInputbarcodes = TextEditingController();
@override
void initState() {
super.initState();
final provider = Provider.of<TestkViewModelScreen>(context, listen: false);
selectedradios = widget.entity['radios'] ?? ''; // Initialize selected radios
scBox = widget.entity['s'] ?? false;
rcBox = widget.entity['r'] ?? false;
fcBox = widget.entity['f'] ?? false;
// Convert the currency value to double if it's not already
if (widget.entity['currency'] is String) {
widget.entity['currency'] =
double.tryParse(widget.entity['currency']) ?? 0.0;
}
// Initially set the controller text without formatting
_inputcurrencyxController.text = widget.entity['currency'].toString();
editedcurrencyxValue = widget.entity['currency'];
inputDataqrcode = widget.entity['qrcode'] ?? "Hello";
controllerInputqrcode = TextEditingController(text: inputDataqrcode);
inputDatabarcodes = widget.entity['barcodes'] ?? "Hello";
controllerInputbarcodes.text = inputDatabarcodes;
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<TestkViewModelScreen>(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 Testk"), actions: [
],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
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(
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 recaptchas",
initialValue: widget.entity['recaptchas'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['recaptchas'] = value,
),
SizedBox(height: 16),
ReusableTextField(
label: "Please Enter documentss",
initialValue: widget.entity['documentss'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['documentss'] = value,
),
SizedBox(height: 16),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Radios",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.blueGrey[900],
),
),
const SizedBox(height: 6),
GestureDetector(
onTap: () => _showradiosSelectionDialog(context),
child: AbsorbPointer(
child: TextFormField(
decoration: InputDecoration(
hintText: "Enter Radios",
border: OutlineInputBorder(),
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
),
controller: TextEditingController(text: selectedradios),
onSaved: (value) {
widget.entity['radios'] = value;
},
),
),
),
const SizedBox(height: 16),
],
),
),
Row(
children: [
Checkbox(
value: scBox,
onChanged: (newValue) {
setState(() {
scBox = newValue!;
});
},
),
const SizedBox(width: 8),
Text('S'),
Checkbox(
value: rcBox,
onChanged: (newValue) {
setState(() {
rcBox = newValue!;
});
},
),
const SizedBox(width: 8),
Text('R'),
Checkbox(
value: fcBox,
onChanged: (newValue) {
setState(() {
fcBox = newValue!;
});
},
),
const SizedBox(width: 8),
Text('F'),
],
),
SizedBox(height: 16),
ReusableTextField(
label: "Please Enter audios",
initialValue: widget.entity['audios'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['audios'] = value,
),
SizedBox(height: 16),
ReusableTextField(
label: "Please Enter videoxx",
initialValue: widget.entity['videoxx'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['videoxx'] = value,
),
SizedBox(height: 16),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: _inputcurrencyxController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Edit Currency Value',
prefixIcon: Icon(Icons.money),
border: OutlineInputBorder(),
),
onChanged: (text) {
setState(() {
try {
String currencyString = text;
currencyString = currencyString.replaceAll(',', ''); // Remove commas
currencyString = currencyString.replaceAll('', ''); // Remove currency symbol
editedcurrencyxValue = double.parse(currencyString);
print("Parsed double value: $editedcurrencyxValue");
} catch (e) {
print("Invalid input: $text");
editedcurrencyxValue = 0.0; // Set to a default value or handle the error accordingly
}
});
},
onSaved: (value) {
widget.entity['currencyx'] = editedcurrencyxValue;
},
),
SizedBox(height: 16),
Text(
'Edited Currency Value: ${editedcurrencyxValue.toStringAsFixed(2)}', // Display formatted currency value
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 16),
// Add other form fields here
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Generate QR Code',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
QrImageView(
data: inputDataqrcode,
version: QrVersions.auto,
size: 200.0,
gapless: false,
),
const SizedBox(height: 16),
TextField(
controller: controllerInputqrcode,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter data for QR code',
),
onChanged: (value) {
setState(() {
inputDataqrcode = value;
widget.entity['qrcode'] = inputDataqrcode;
});
},
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'Generate Barcode',
style: TextStyle(fontSize: 18),
),
const SizedBox(height: 16),
if (inputDatabarcodes.isNotEmpty)
BarcodeWidget(
barcode: Barcode.code128(), // Choose the type of barcode
data: inputDatabarcodes,
width: 200,
height: 80,
),
const SizedBox(height: 16),
TextField(
controller: controllerInputbarcodes,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter data for barcode',
),
onChanged: (value) {
setState(() {
inputDatabarcodes = value;
widget.entity['barcodes'] = inputDatabarcodes;
});
},
),
const SizedBox(height: 16),
// ElevatedButton(
// onPressed: () {
// setState(() {
// inputData = controllerInput.text;
// });
// },
// child: const Text('Generate Barcode'),
// ),
],
),
const 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['s'] = scBox;
widget.entity['r'] = rcBox;
widget.entity['f'] = fcBox;
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 Testk: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
},
),
],
),
),
),
),
);
}
}

View File

@ -0,0 +1,124 @@
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 TestkRepoScreen {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<dynamic> getEntities() async {
try {
final response =
await _helper.getGetApiResponse('$baseUrl/Testk/Testk');
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/Testk/Testk/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/Testk/Testk', 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/Testk/Testk/$entityId', entity);
print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity(int entityId) async {
try {
await _helper
.getDeleteApiResponse('$baseUrl/Testk/Testk/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
Future<dynamic> fileuploadxUpload(
String ref, String refTableNmae, FormData entity) async {
try {
String apiUrl = "$baseUrl/FileUpload/Uploadeddocs/$ref/$refTableNmae";
final response = await _helper.getPostApiResponse(apiUrl, entity);
return response;
} catch (e) {
throw Exception('Failed to Upload File: $e');
}
}
Future<dynamic> imageuploadaUpload(
String ref, String refTableNmae, FormData entity) async {
try {
String apiUrl = "$baseUrl/FileUpload/Uploadeddocs/$ref/$refTableNmae";
final response = await _helper.getPostApiResponse(apiUrl, entity);
return response;
} catch (e) {
throw Exception('Failed to Upload Imageuploada: $e');
}
}
Future<dynamic> audiosUpload(
String ref, String refTableNmae, FormData entity) async {
try {
String apiUrl = "$baseUrl/FileUpload/Uploadeddocs/$ref/$refTableNmae";
final response = await _helper.getPostApiResponse(apiUrl, entity);
return response;
} catch (e) {
throw Exception('Failed to Upload File: $e');
}
}
Future<dynamic> videoxxUpload(
String ref, String refTableNmae, FormData entity) async {
try {
String apiUrl = "$baseUrl/FileUpload/Uploadeddocs/$ref/$refTableNmae";
final response = await _helper.getPostApiResponse(apiUrl, entity);
return response;
} catch (e) {
throw Exception('Failed to Upload File: $e');
}
}
}

View File

@ -0,0 +1,336 @@
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 '../Testk_Repo/Testk_repo_screen.dart';
class TestkViewModelScreen extends ChangeNotifier{
final TestkRepoScreen repo = TestkRepoScreen();
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');
}
}
// Modify the uploadfileuploadximage function
Future<void> uploadfileuploadx(String ref, String refTableNmae,
String selectedFilePath, Uint8List imageTimageBytes) async {
try {
final Uint8List fileBytes = imageTimageBytes!;
final mimeType = fileuploadxlookupMimeType(selectedFilePath);
FormData formData = FormData.fromMap({
'file': MultipartFile.fromBytes(
fileBytes,
filename: selectedFilePath
.split('/')
.last, // Get the file name from the path
contentType: MediaType.parse(mimeType!),
),
});
await repo.fileuploadxUpload(ref, refTableNmae, formData).then((value) {
ToastMessageUtil.showToast(
message: "File uploaded successfully",
toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Failed to upload file", toastType: ToastType.error);
},
);
} catch (error) {
print('Error occurred during form submission: $error');
}
}
// Modify the lookupMimeType function if needed
String fileuploadxlookupMimeType(String filePath) {
final ext = filePath.split('.').last;
switch (ext) {
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'pdf':
return 'application/pdf';
// Add more cases for other file types as needed
default:
return 'application/octet-stream'; // Default MIME type
}
}
// Modify the uploadimageuploadaimage function
Future<void> uploadimageuploada(String ref, String refTableNmae,
String selectedFilePath, Uint8List image_timageBytes) async {
try {
final Uint8List fileBytes = image_timageBytes!;
final mimeType = imageuploadalookupMimeType(selectedFilePath);
FormData formData = FormData.fromMap({
'file': MultipartFile.fromBytes(
fileBytes,
filename: selectedFilePath
.split('/')
.last, // Get the file name from the path
contentType: MediaType.parse(mimeType!),
),
});
await repo.imageuploadaUpload(ref, refTableNmae, formData).then((value) {
ToastMessageUtil.showToast(
message: "File uploaded successfully",
toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Failed to upload file", toastType: ToastType.error);
},
);
} catch (error) {
print('Error occurred during form submission: $error');
}
}
// Modify the lookupMimeType function if needed
String imageuploadalookupMimeType(String filePath) {
final ext = filePath.split('.').last;
switch (ext) {
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'pdf':
return 'application/pdf';
// Add more cases for other file types as needed
default:
return 'application/octet-stream'; // Default MIME type
}
}
// Modify the uploadaudiosimage function
Future<void> uploadaudios(String ref, String refTableNmae,
String selectedFilePath, Uint8List image_timageBytes) async {
try {
final Uint8List fileBytes = image_timageBytes!;
final mimeType = audioslookupMimeType(selectedFilePath);
FormData formData = FormData.fromMap({
'file': MultipartFile.fromBytes(
fileBytes,
filename: selectedFilePath
.split('/')
.last, // Get the file name from the path
contentType: MediaType.parse(mimeType!),
),
});
await repo.audiosUpload(ref, refTableNmae, formData).then((value) {
ToastMessageUtil.showToast(
message: "File uploaded successfully",
toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Failed to upload file", toastType: ToastType.error);
},
);
} catch (error) {
print('Error occurred during form submission: $error');
}
}
// Modify the lookupMimeType function if needed
String audioslookupMimeType(String filePath) {
final ext = filePath.split('.').last.toLowerCase();
switch (ext) {
case 'mp3':
return 'audio/mpeg';
case 'wav':
return 'audio/wav';
case 'm4a':
return 'audio/mp4';
case 'flac':
return 'audio/flac';
// Add more cases for other audio formats as needed
default:
return 'application/octet-stream'; // Default MIME type
}
}
// Modify the uploadvideoxximage function
Future<void> uploadvideoxx(String ref, String refTableNmae,
String selectedFilePath, Uint8List image_timageBytes) async {
try {
final Uint8List fileBytes = image_timageBytes!;
final mimeType = videoxxlookupMimeType(selectedFilePath);
FormData formData = FormData.fromMap({
'file': MultipartFile.fromBytes(
fileBytes,
filename: selectedFilePath
.split('/')
.last, // Get the file name from the path
contentType: MediaType.parse(mimeType!),
),
});
await repo.videoxxUpload(ref, refTableNmae, formData).then((value) {
ToastMessageUtil.showToast(
message: "File uploaded successfully",
toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Failed to upload file", toastType: ToastType.error);
},
);
} catch (error) {
print('Error occurred during form submission: $error');
}
}
// Modify the lookupMimeType function if needed
String videoxxlookupMimeType(String filePath) {
final ext = filePath.split('.').last.toLowerCase();
switch (ext) {
case 'mp4':
return 'video/mp4';
case 'mov':
return 'video/quicktime';
case 'avi':
return 'video/x-msvideo';
case 'wmv':
return 'video/x-ms-wmv';
case 'flv':
return 'video/x-flv';
case 'mkv':
return 'video/x-matroska';
// Add more cases for other file types as needed
default:
return 'application/octet-stream'; // Default MIME type
}
}
}

View File

@ -1,3 +1,6 @@
import '../../Entity/forma/Testk/TestkView/Testk_entity_list_screen.dart';
import '../../Entity/forma/Testk/Testk_viewModel/Testk_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: 'Testk',
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => TestkViewModelScreen(),
child: testk_entity_list_screen(),
),
),
);
},
),
],
),
);
}
DrawerItem(
icon: Icons.logout,
color: Colors.red,
title: 'Logout',
onTap: () async {
await UserManager().clearUser();
Navigator.pushReplacementNamed(context, RouteNames.splashView);
},
),
],
),
);
}
}