Files
Regroup/lib/Feed Module/Main_Screens/ProfileTab/TimeLine/AddTimeline.dart
2024-08-20 20:01:30 +05:30

978 lines
49 KiB
Dart

import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:regroup/Common/CommonGlassmorphism.dart';
import 'package:regroup/Common/CommonWidget.dart';
import 'package:regroup/Common/base_manager.dart';
import 'package:regroup/Main_Screens/ProfileTab/Model/timelineabilityModel.dart' as timelineabilist;
import 'package:regroup/Main_Screens/ProfileTab/view_model/gettimelineability.dart';
import 'package:regroup/Main_Screens/ProfileTab/view_model/profileGetmethod.dart';
import 'package:regroup/Main_Screens/ProfileTab/view_model/profilePostmethod.dart';
import 'package:regroup/Utils/Common/CommonAppbar.dart';
import 'package:regroup/Utils/Common/CommonDropdown.dart';
import 'package:regroup/Utils/Common/CustomNextButton.dart';
import 'package:regroup/Utils/Common/CustomTextformfield.dart';
import 'package:regroup/Utils/Common/sized_box.dart';
import 'package:regroup/Utils/dialogs.dart';
import 'package:regroup/Utils/texts.dart';
import 'package:regroup/resources/routes/route_name.dart';
import 'package:remove_emoji_input_formatter/remove_emoji_input_formatter.dart';
import 'package:intl/intl.dart';
import 'package:async/src/future_group.dart';
class AddTimeline extends StatefulWidget {
const AddTimeline({super.key});
@override
State<AddTimeline> createState() => _AddTimelineState();
}
class _AddTimelineState extends State<AddTimeline> {
TextEditingController dateController = TextEditingController();
TextEditingController dateController2 = TextEditingController();
TextEditingController clubNameController = TextEditingController();
TextEditingController rollnameController = TextEditingController();
TextEditingController teamnameController = TextEditingController();
int id = Get.arguments["id"];
bool edited = Get.arguments["edit"];
RxBool isChecked = false.obs;
timelineabilist.TimelineAbilityListModel? abilityModel;
List<timelineabilist.Data> timeline = [];
List<String> _abilitydrop = [];
Future<void> fetchABilitylist() async {
TimelineAbilityListApi abilityLsitAPI = TimelineAbilityListApi();
ResponseData<dynamic> response = await abilityLsitAPI.getAbilitylistApi();
if (response.status == ResponseStatus.SUCCESS) {
abilityModel =
timelineabilist.TimelineAbilityListModel.fromJson(response.data!);
setState(() {
timeline = abilityModel!.data ?? []; // Store the fetched cities
_abilitydrop =
timeline.map((platform) => platform.name.toString()).toList();
});
log(timeline.toString());
} else {
print('Failed to fetch abilities');
}
}
List<int> selectedabilityid = [];
void getCatIdFromName(List<String> selectedAbilities) {
selectedabilityid.clear(); // Clear existing selections
for (var name in selectedAbilities) {
for (var i = 0; i < timeline.length; i++) {
if (name == timeline[i].name) {
selectedabilityid.add(timeline[i].id!);
break; // Assuming each name is unique, we break after finding a match
}
}
}
}
// late Future myfuture;
FutureGroup futureGroup = FutureGroup();
RxBool isloading = true.obs;
List<String> seelctedNameList = [];
@override
void initState() {
// TODO: implement initState
if (edited == true) {
// futureGroup.add(
Profilegetmethod().getEditTimeline(id).then((value) {
clubNameController.text =
edittimelineobj!.data!.timelineData!.clubName ?? "";
rollnameController.text =
edittimelineobj!.data!.timelineData!.roleName ?? "";
teamnameController.text =
edittimelineobj!.data!.timelineData!.teamName ?? "";
"";
dateController.text =
edittimelineobj!.data!.timelineData!.startDate ?? "";
dateController2.text =
edittimelineobj!.data!.timelineData!.endDate ?? "";
log(_abilityMap.length.toString());
// futureGroup.add(
fetchABilitylist().then((value) {
String abilitiesXids =
edittimelineobj!.data!.timelineData!.abilitiesXids ?? "";
abilitiesIds = abilitiesXids
.split(',')
.map((e) => int.tryParse(e.trim()) ?? 0) // Trim spaces around IDs
.toList();
selectedabilityid = abilitiesIds;
print(selectedabilityid.toList());
for (int i = 0; i < _abilitydrop.length; i++) {
_abilityMap.add({
"id": i + 1,
"name": _abilitydrop[i],
});
}
getSelectedNames(selectedabilityid).then((value) {
seelctedNameList = value;
isloading = false.obs;
});
});
// );
});
} else {
fetchABilitylist().then((value) {
isloading = false.obs;
});
}
super.initState();
}
List<int> abilitiesIds = [];
UploadData() async {
// SharedPreferences prefs = await SharedPreferences.getInstance();
utils.loader();
String abilitiesIds = selectedabilityid.join(',');
print(abilitiesIds);
Map<String, dynamic> updata = {
"club_name": clubNameController.text,
"role_name": rollnameController.text,
"team_name": teamnameController.text,
"start_date": dateController.text,
"end_date": dateController2.text,
"abilities_xids": abilitiesIds,
};
final data = await Profilepostmethod().postTimeline(updata);
if (data.status == ResponseStatus.SUCCESS) {
Get.back();
// Get.back();
// await EditProfileApi().getEditProfileIndividual().then((value) {
// Get.back();
// });
Get.toNamed(RouteName.mainscreen, arguments: 4);
print("timeline done");
return utils.showToast(data.message);
} else {
Get.back();
print("timeline not done");
return utils.showToast(data.message);
}
}
EdituploadData() async {
utils.loader();
String abilitiesIds = selectedabilityid.join(',');
print(abilitiesIds);
Map<String, dynamic> updata = {
"club_name": clubNameController.text,
"role_name": rollnameController.text,
"team_name": teamnameController.text,
"start_date": dateController.text,
"end_date": dateController2.text,
"abilities_xids": abilitiesIds,
"timeline_id": id,
};
final data = await Profilepostmethod().postEditTimeline(updata);
if (data.status == ResponseStatus.SUCCESS) {
Get.back();
print("timeline done");
// await EditProfileApi().getEditProfileIndividual().then((value) {
// Get.back();
// });
// utils.showToast(data.message);
// await Future.delayed(
// Duration(milliseconds: 500)); // Add a small delay if needed
// Get.toNamed(RouteName.mainscreen, arguments: 4);
Get.toNamed(RouteName.mainscreen, arguments: 4);
} else {
Get.back();
print("timeline not done");
return utils.showToast(data.message);
}
}
// List<Map<String, dynamic>> _abilityMap = [];
List<Map<String, dynamic>> _abilityMap = [];
List<String> listData = [];
// Function to get names from selected IDs
Future<List<String>> getSelectedNames(List<int> selectedIds) async {
List<String> selectedNames = [];
for (int id in selectedIds) {
for (Map<String, dynamic> ability in _abilityMap) {
if (ability["id"] == id) {
selectedNames.add(ability["name"]);
break;
}
}
_abilitydrop =
_abilityMap.map((ability) => ability["name"] as String).toList();
}
return selectedNames;
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Scaffold(
// resizeToAvoidBottomInset: false,
// key: _scaffoldKey1,
backgroundColor: Color(0xFF222935),
extendBody: true,
appBar: CommonAppbar(
titleTxt: "Add timeline",
),
body: Obx(()
// {
=>
isloading.value
? Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
],
))
: edited == true
? Stack(children: [
Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(
"assets/images/png/Ellipse 1496.png"),
fit: BoxFit.fill)),
),
ListView(physics: ScrollPhysics(), children: [
Padding(
padding:
EdgeInsets.symmetric(horizontal: 16.w),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
sizedBoxHeight(20.h),
text16400white("Club name"),
sizedBoxHeight(15.h),
CustomTextFormField(
textEditingController:
clubNameController,
texttype: TextInputType.text,
hintText: 'Enter club name',
validator: (value) {
if (value!.isEmpty) {
return 'Enter your club name ';
}
return null;
},
inputFormatters: [
// LengthLimitingTextInputFormatter(20),
RemoveEmojiInputFormatter(),
FilteringTextInputFormatter.allow(
RegExp('[a-zA-Z ]'))
],
),
sizedBoxHeight(25.h),
text16400white("Role in "),
sizedBoxHeight(15.h),
CustomTextFormField(
textEditingController:
rollnameController,
texttype: TextInputType.text,
hintText: 'Enter role in the club',
validator: (value) {
if (value!.isEmpty) {
return 'Enter role in the club';
}
return null;
},
inputFormatters: [
// LengthLimitingTextInputFormatter(20),
RemoveEmojiInputFormatter(),
FilteringTextInputFormatter.allow(
RegExp('[a-zA-Z ]'))
],
),
sizedBoxHeight(25.h),
text16400white("Team name"),
sizedBoxHeight(15.h),
CustomTextFormField(
textEditingController:
teamnameController,
texttype: TextInputType.text,
hintText: 'Enter team name',
validator: (value) {
if (value!.isEmpty) {
return 'Enter your team name ';
}
return null;
},
inputFormatters: [
// LengthLimitingTextInputFormatter(20),
RemoveEmojiInputFormatter(),
FilteringTextInputFormatter.allow(
RegExp('[a-zA-ZS0-9 ]')),
],
),
sizedBoxHeight(25.h),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
text16400white("Start date "),
sizedBoxHeight(10.h),
GestureDetector(
onTap: () => datePicker(
context,
dateController),
child: AbsorbPointer(
child:
CustomTextFormField(
textEditingController:
dateController,
leadingIcon: Container(
height: 20.h,
width: 20.w,
child: Center(
child: Image.asset(
"assets/images/png/calender.png",
height: 20.h,
width: 20.w,
),
),
),
),
),
)
],
),
),
sizedBoxWidth(10.h),
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
text16400white("End date"),
sizedBoxHeight(10.h),
GestureDetector(
onTap: () => datePicker(
context,
dateController2),
child: AbsorbPointer(
child:
CustomTextFormField(
textEditingController:
dateController2,
leadingIcon: Container(
height: 20.h,
width: 20.w,
child: Center(
child: Image.asset(
"assets/images/png/calender.png",
height: 20.h,
width: 20.w,
),
),
),
),
),
),
sizedBoxHeight(10.h),
Row(
children: [
Obx(() {
return commonGlassUI(
borderwidth: 1,
borderRadius: BorderRadius.circular(2),
height: 20.h,
width: 20.w,
opacity1: 0.24,
opacity2: 0.24,
customWidget:
Transform.scale(
scale: 1.2,
child: Checkbox(
side: BorderSide(
color: Color(
0xFF434A53)),
value: isChecked
.value,
activeColor: Colors
.transparent,
checkColor:
Colors.white,
onChanged:
((value) {
// isChecked.value = value!;
isChecked
.value =
value!;
if (isChecked
.value) {
// Set end date to today's date
dateController2
.text = DateFormat(
'yyyy-MM-dd')
.format(DateTime
.now());
} else {
// Clear end date when checkbox is unchecked
dateController2
.clear();
}
}),
),
),
);
}),
sizedBoxWidth(8.w),
text10400white("Present")
],
),
],
),
)
],
),
text16400white("Ability"),
sizedBoxHeight(15.h),
// CustomDropDownCheckBoxTimeline(
// header: 'Select ability',
// title: '',
// listData: _abilitydrop,
// onItemSelected: getCatIdFromName,
// initiallySelected: abilitiesIds
// .map((id) => id.toString())
// .toList(),
// ),
CustomDropDownCheckBoxTimeline(
header: 'Select ability',
title: '',
listData: _abilitydrop,
// _abilityMap.map((ability) => ability["name"]).toList(),
onItemSelected: getCatIdFromName,
// (selectedNames) {
// // Convert selected names back to IDs if needed
// List<int> selectedIds = [];
// for (String name in selectedNames) {
// for (Map<String, dynamic> ability
// in _abilityMap) {
// if (ability["name"] == name) {
// selectedIds.add(ability["id"]);
// break;
// }
// }
// }
// // Use selectedIds as needed
// print(selectedIds);
// },
initiallySelected:
seelctedNameList, // Pass initially selected names
),
sizedBoxHeight(80.h),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 20.w),
child: CustomButton(
text: "Add timeline",
onPressed: () {
if (clubNameController.text.isBlank! ||
rollnameController
.text.isBlank! ||
teamnameController
.text.isBlank! ||
dateController
.text.isBlank! ||
dateController2
.text.isBlank! ||
selectedabilityid.isEmpty) {
utils.showToast(
'Please fill all fields');
} else {
print(selectedabilityid
.toString());
EdituploadData();
}
},
),
),
]),
)
])
])
: Stack(children: [
Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(
"assets/images/png/Ellipse 1496.png"),
fit: BoxFit.fill)),
),
ListView(physics: ScrollPhysics(), children: [
Padding(
padding:
EdgeInsets.symmetric(horizontal: 16.w),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
sizedBoxHeight(20.h),
text16400white("Club name"),
sizedBoxHeight(15.h),
CustomTextFormField(
textEditingController:
clubNameController,
texttype: TextInputType.text,
hintText: 'Enter club name',
validator: (value) {
if (value!.isEmpty) {
return 'Enter your full name ';
}
return null;
},
inputFormatters: [
// LengthLimitingTextInputFormatter(20),
RemoveEmojiInputFormatter(),
FilteringTextInputFormatter.allow(
RegExp('[a-zA-Z ]'))
],
),
sizedBoxHeight(25.h),
text16400white("Role in the club"),
sizedBoxHeight(15.h),
CustomTextFormField(
textEditingController:
rollnameController,
texttype: TextInputType.text,
hintText: 'Enter role in the club',
validator: (value) {
if (value!.isEmpty) {
return 'Enter role in the club';
}
return null;
},
inputFormatters: [
// LengthLimitingTextInputFormatter(20),
RemoveEmojiInputFormatter(),
FilteringTextInputFormatter.allow(
RegExp('[a-zA-Z ]'))
],
),
sizedBoxHeight(25.h),
text16400white("Team name"),
sizedBoxHeight(15.h),
CustomTextFormField(
textEditingController:
teamnameController,
texttype: TextInputType.text,
hintText: 'Enter team name',
validator: (value) {
if (value!.isEmpty) {
return 'Enter your team name ';
}
return null;
},
inputFormatters: [
// LengthLimitingTextInputFormatter(20),
RemoveEmojiInputFormatter(),
FilteringTextInputFormatter.allow(
RegExp('[a-zA-ZS0-9 ]')),
],
),
sizedBoxHeight(25.h),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
text16400white("Start date "),
sizedBoxHeight(10.h),
GestureDetector(
onTap: () => datePicker(
context,
dateController),
child: AbsorbPointer(
child:
CustomTextFormField(
textEditingController:
dateController,
leadingIcon: Container(
height: 20.h,
width: 20.w,
child: Center(
child: Image.asset(
"assets/images/png/calender.png",
height: 20.h,
width: 20.w,
),
),
),
),
),
)
],
),
),
sizedBoxWidth(10.h),
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
text16400white("End date"),
sizedBoxHeight(10.h),
GestureDetector(
onTap: () => datePicker(
context,
dateController2),
child: AbsorbPointer(
child:
CustomTextFormField(
textEditingController:
dateController2,
leadingIcon: Container(
height: 20.h,
width: 20.w,
child: Center(
child: Image.asset(
"assets/images/png/calender.png",
height: 20.h,
width: 20.w,
),
),
),
),
),
),
sizedBoxHeight(10.h),
Row(
children: [
Obx(() {
return commonGlassUI(
borderwidth: 1,
borderRadius: BorderRadius.circular( 2),
height: 20.h,
width: 20.w,
opacity1: 0.24,
opacity2: 0.24,
customWidget:
Transform.scale(
scale: 1.2,
child: Checkbox(
side: BorderSide(
color: Color(
0xFF434A53)),
value: isChecked
.value,
activeColor: Colors
.transparent,
checkColor:
Colors.white,
onChanged:
((value) {
// isChecked.value = value!;
isChecked
.value =
value!;
if (isChecked
.value) {
// Set end date to today's date
dateController2
.text = DateFormat(
'yyyy-MM-dd')
.format(DateTime
.now());
} else {
// Clear end date when checkbox is unchecked
dateController2
.clear();
}
}),
),
),
);
}),
sizedBoxWidth(8.w),
text10400white("Present")
],
),
],
),
)
],
),
text16400white("Ability"),
sizedBoxHeight(15.h),
CustomDropDownChexkBox(
header: 'Select ability',
title: '',
listData: _abilitydrop,
onItemSelected: getCatIdFromName,
initiallySelected: [], // or pass initial values if needed
),
sizedBoxHeight(80.h),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 20.w),
child: CustomButton(
text: "Add timeline",
onPressed: () {
if (clubNameController.text.isBlank! ||
rollnameController
.text.isBlank! ||
teamnameController
.text.isBlank! ||
dateController
.text.isBlank! ||
dateController2
.text.isBlank! ||
selectedabilityid.isEmpty) {
utils.showToast(
'Please fill all fields');
} else {
print(selectedabilityid
.toString());
UploadData();
}
},
),
),
]),
)
])
])
// }
)),
);
}
}
class CustomDropDownCheckBoxTimeline extends StatefulWidget {
const CustomDropDownCheckBoxTimeline({
Key? key,
required this.header,
required this.title,
required this.listData,
required this.onItemSelected,
this.leadingImage,
this.showOtherOption = false,
required this.initiallySelected,
}) : super(key: key);
final String header;
final String title;
final List<String> listData;
final Function(List<String>) onItemSelected;
final Widget? leadingImage;
final bool showOtherOption;
final List<String> initiallySelected;
@override
State<CustomDropDownCheckBoxTimeline> createState() =>
_CustomDropDownCheckBoxTimelineState();
}
class _CustomDropDownCheckBoxTimelineState
extends State<CustomDropDownCheckBoxTimeline> {
RxBool onDropTap = false.obs;
RxList<String> selectedValues = <String>[].obs;
final TextEditingController _textController = TextEditingController();
@override
void initState() {
super.initState();
selectedValues
.addAll(widget.initiallySelected); // Initialize selectedValues
}
List<DropdownMenuItem<String>> _buildDropdownMenuItems() {
return widget.listData.asMap().entries.map((entry) {
int index = entry.key;
String item = entry.value;
return DropdownMenuItem<String>(
value: item,
child: InkWell(
onTap: () {
setState(() {
if (selectedValues.contains(item)) {
selectedValues.remove(item);
} else {
selectedValues.add(item);
}
_textController.clear();
widget.onItemSelected(selectedValues.toList());
});
},
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
children: [
Obx(() {
return Checkbox(
value: selectedValues.contains(item),
activeColor: Colors.white,
checkColor: const Color(0xFFD90B2E),
onChanged: (bool? value) {
setState(() {
if (value == true) {
selectedValues.add(item);
} else {
selectedValues.remove(item);
}
_textController.clear();
widget.onItemSelected(selectedValues.toList());
});
},
);
}),
const SizedBox(width: 8),
Expanded(
child: Text(
item,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontFamily: 'Helvetica',
fontWeight: FontWeight.w500,
),
maxLines: 1, // Adjust as needed
overflow: TextOverflow.ellipsis,
),
),
],
),
if (index != widget.listData.length - 1)
const Divider(thickness: 1, color: Color(0xFF434A53)),
],
),
),
);
}).toList();
}
@override
Widget build(BuildContext context) {
return Obx(
() => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () {
onDropTap.value = !onDropTap.value;
},
child: Container(
width: double.infinity,
// height: 50,
padding:
EdgeInsets.only(right: 22, left: 12, top: 15, bottom: 15),
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF).withOpacity(0.10),
borderRadius: onDropTap.value
? const BorderRadius.vertical(
top: Radius.circular(30),
)
: const BorderRadius.all(Radius.circular(30)),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
const Color(0xFFffffff).withOpacity(0.50),
const Color(0xFFFFFFFF).withOpacity(0.50),
],
),
border: Border.all(color: const Color(0xFF434A53)),
),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
widget.leadingImage == null
? SizedBox()
: widget.leadingImage!,
const SizedBox(width: 12),
Expanded(
child: Text(
selectedValues.isEmpty
? widget.header
: selectedValues.join(', '),
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontFamily: 'Helvetica',
fontWeight: FontWeight.w400,
),
// overflow: TextOverflow.ellipsis,
),
),
// const Spacer(),
onDropTap.value
? Image.asset('assets/images/png/arrowup.png')
: Image.asset('assets/images/png/arrowdown.png'),
],
),
),
),
),
if (onDropTap.value)
Scrollbar(
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF).withOpacity(0.10),
borderRadius: const BorderRadius.vertical(
bottom: Radius.circular(30),
),
border: Border.all(color: const Color(0xFF434A53)),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
const Color(0xFFffffff).withOpacity(0.50),
const Color(0xFFFFFFFF).withOpacity(0.50),
],
),
),
child: Column(
children: _buildDropdownMenuItems(),
),
),
),
],
),
);
}
}