How can I call OnvalueChanged in flutter? - flutter

I want to add page ==> Like tab bar
I want to add like 2 pages - in this SegmentsBar...
How can I achieve it?
this is my code ---
[
final _segments = <String, String>{
'freelancher': 'Freelancer',
'employer': 'Employer',
};
var _value = 'freelancher';
AdvancedSegment(
sliderOffset: 5,
sliderColor: Colors.white,
backgroundColor: Colors.white24,
shadow: [
BoxShadow(
color: Colors.transparent,
),
],
activeStyle: TextStyle(
fontFamily: AppTheme.medium,
color: AppTheme.primaryColor,
),
inactiveStyle: TextStyle(
fontFamily: AppTheme.medium,
color: AppTheme.white,
),
itemPadding: EdgeInsets.symmetric(
horizontal: 45,
vertical: 10,
),
segments: _segments,
controller: _advanceC,
onValueChanged: (value) {
_value == value ? ChatPage() : ProfilePage();
},
value: _value,
),
I need help please.
Thanks Buddy.

I don't know what is AdvancedSegment, use instead AnimatedPositioned
onValueChanged:
(value) {
setState(() {
_value == value ? ChatPage() : ProfilePage();
});
}

Related

Clear the selected value in dropdown_button2 flutter

I am using dropdown_button2 for dropdown feature.How to clear the value in this dropdown when close the screen.?
DropdownButtonHideUnderline(
child: DropdownButton2<CategoryList>(
hint: Text(
'Select Item',
style: GoogleFonts.inter(
fontSize: 13,
),
),
items: collectionController. libContentGetResponse2.value.data!.rows!
.map((item) =>
DropdownMenuItem<CategoryList>(
value: item,
child: Text(
item.categoryName.toString(),
style: const TextStyle(
fontSize: 14,
),
),
))
.toList(),
value: getSelected(),
onChanged: (CategoryList? value) {
collectionController.selectItem.value = value!;
},
dropdownMaxHeight: 200,
buttonWidth: MediaQuery.of(conText).size.width / 2.7,
buttonPadding: const EdgeInsets.only(left: 14, right: 14),
buttonDecoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
border: Border.all(color: Color(0xffD9D9D9),width: 1),
),
),
)
CategoryList? getSelected() {
if (collectionController.selectItem.value == null) return null;
try {
var selectedIndex = collectionController. libContentGetResponse2.value.data!.rows!
.indexWhere((element) => element.categoryName == collectionController.selectItem.value .categoryName);
if (selectedIndex != -1)
return collectionController. libContentGetResponse2.value.data!.rows![selectedIndex];
else
return null;
} catch (e) {
return null;
}
}
Now my CategoryList has two values ["A", "B"]. I selected A and navigated to another screen then again opened the screen which has this dropdown button. Instead of showing the hint, the previously selected item is displayed there.

How to change button color and move to home when selecting 5 checklists or selecting all in flutter

I'm making a contract terms page. Checkbox ListTile is being used.
There is a total agreement and six items.
If the first to fifth items of the Terms and Conditions are selected, the Elevated Button color should be changed to blue and made available to move home (screenshot).
If all items are selected, the Elevated Button color should be changed to blue and made to be able to move home (screenshot).
Other than that, Elevated Button is grey and cannot be moved home (screenshot).
I tried it, but it's so hard to set the index for each item
Is there a solution?
Thank you to those who answered.
class TermsAgreementPage extends StatelessWidget {
TermsAgreementPage({
Key? key,
}) : super(key: key);
CheckBoxState checkBoxState = Get.put(CheckBoxState(''));
final alltermsAndConditions = CheckBoxState('');
final termsAndConditions = [
CheckBoxState('이용 약관 동의(필수)', '니어엑스 서비스 이용 통합 약관입니다.'),
CheckBoxState('개인정보 처리방침 동의(필수)', '개인정보보호 포털 법률에 의거한 제공동의로 필수 사항입니다.'),
CheckBoxState('개인정보 제3자 제공동의(필수)', '개인정보보호 포털 법률에 의거한 제공 동의로 필수 사항입니다.'),
CheckBoxState('위치기반 서비스 이용약관(필수)', '주변 가게들 검색에 사용됩니다.'),
CheckBoxState('전자금융거래 이용약관(필수)', '구매 또는 결제 사항이 있을 경우 제공 동의로 필수 사항입니다.'),
CheckBoxState('니어엑스 혜택 알림 동의(선택)','미선택 시 주변가게 할인 및 만기 다가오는 쿠폰 알림 사용 불가.')
];
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
body: Padding(
padding: const EdgeInsets.only(top: 80.0, bottom: 40),
child: Column(
children: [
Expanded(
flex: 1,
child: SizedBox(
width: size.width,
child: Column(
children: const [
Text(
'이용 약관 동의',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
Text(
'아래의 약관에 동의 하신 후 서비스를 이용해 주시기 바랍니다.',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.grey),
),
],
),
),
),
Expanded(
flex: 6,
child: Obx(
() => ListView(
children: [
buildGroupCheckbox(CheckBoxState('전체동의')),
Divider(color: Colors.grey[300], height: 5, thickness: 3),
...termsAndConditions.map(buildCheckbox).toList(),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: termsAndConditions.every((termsAndConditions) => termsAndConditions.isChecked.value)
? Colors.blue
: Colors.grey[400],
padding: const EdgeInsets.symmetric(
horizontal: 150, vertical: 10),
textStyle: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w400,
color: Colors.white)),
onPressed: () {
if(alltermsAndConditions.isChecked.value) {
Get.toNamed('/home');
}
},
child: const Text('시작하기'),
),
],
),
),
),
],
),
),
);
}
Widget buildGroupCheckbox(CheckBoxState checkBoxState) {
return CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
secondary: TextButton(
onPressed: () {
Get.toNamed('/home');
},
child: const Text(
'전문보기',
style: TextStyle(fontSize: 10.0, color: Colors.blue),
)),
title: Text(
checkBoxState.title,
style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
),
onChanged: toggleCheckBox,
value: alltermsAndConditions.isChecked.value,
);
}
void toggleCheckBox(bool? value) {
if (value == null) return;
alltermsAndConditions.isChecked.value = value;
for (var termsAndConditions in termsAndConditions) {
termsAndConditions.isChecked.value = value;
}
}
Widget buildCheckbox(CheckBoxState checkBoxState) {
return CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
title: Text(
checkBoxState.title,
style: const TextStyle(fontSize: 12),
),
subtitle: Text(
checkBoxState.subTitle,
style: const TextStyle(fontSize: 9, color: Colors.grey),
),
onChanged: (value) {
checkBoxState.isChecked.value = value!;
alltermsAndConditions.isChecked.value = termsAndConditions.every(
(termsAndConditions) => termsAndConditions.isChecked.value);
},
value: checkBoxState.isChecked.value // checkBoxState 의 isChecked 값임 (false 상태)
);
}
}
class CheckBoxState extends GetxController {
RxBool isChecked = false.obs;
String title;
String subTitle;
CheckBoxState(this.title,[this.subTitle = '']);
}
It's possible to use getRange to get the items from 0 to 4 (The first 5 items). And then, just iterate over every one of them to check if all of them are checked.
Just change the line:
primary: termsAndConditions.every((termsAndConditions) => termsAndConditions.isChecked.value)
? Colors.blue
: Colors.grey[400],
To the following:
primary: termsAndConditions.getRange(0, 4).every(
(termsAndConditions) => termsAndConditions.isChecked.value)
? Colors.blue
: Colors.grey[400],
And also the onPressed property from:
onPressed: () {
if (allTermsAndConditions.isChecked.value) {
Get.toNamed('/home');
}
},
To the following:
onPressed: () {
if (termsAndConditions.getRange(0, 4).every(
(termsAndConditions) =>
termsAndConditions.isChecked.value)) {
Get.toNamed('/home');
}
},

How can i print checkbox value on Text() Widget using Flutter

Is there a way to print checkbox value in a Text widget Eg. I make two checkbox which have a value of POD and Prepaid i would like to print out the selected checkbox value on Text() Widget.
Code:-
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Checkbox(
value: prepaidCheckBoxValue,
shape: const CircleBorder(),
checkColor: Colors.white,
onChanged: (value) {
prepaidCheckBoxValue = !prepaidCheckBoxValue;
//print(prepaidCheckBoxValue);
setState(() {});
},
),
const Text(
'Prepaid',
style: TextStyle(
fontSize: 20.0,
),
),
const SizedBox(
width: 30.0,
),
Checkbox(
value: podCheckBoxValue,
shape: const CircleBorder(),
checkColor: Colors.white,
onChanged: (value) {
podCheckBoxValue = !podCheckBoxValue;
setState(() {});
//print(value);
},
),
const Text(
'Pay on Delivery',
style: TextStyle(
fontSize: 20.0,
),
),
],
),
),
My recommendation
create a enum for payment methods
enum PaymentTypes {
prepaid,
pay_on_delivery,
}
create a local variable to store selected payment method in your state class
PaymentTypes selectedPaymentType;
set the selected payment method on checkbox onChange method
Checkbox(
//prepaid checkbox
...
onChanged: (value) {
podCheckBoxValue = !podCheckBoxValue;
setState(() {
selectedPaymentType = PaymentTypes.prepaid;
});
//print(value);
},
),
Checkbox(
//pay on delivery checkbox
...
onChanged: (value) {
podCheckBoxValue = !podCheckBoxValue;
setState(() {
selectedPaymentType = PaymentTypes.pay_on_delivery;
});
//print(value);
},
),
use selectedPaymentType value on Textbox
const Text(
describeEnum(selectedPaymentType).replaceAll(RegExp('_'), ' ')
)
Or you can just use a string to store the checkbox value without enums
String selectedPaymentType;
onChanged: (value) {
podCheckBoxValue = !podCheckBoxValue;
setState(() {
selectedPaymentType = 'Pay on delivery';
});
//print(value);
},
),
const Text(
selectedPaymentType
)

Flutter how to clean this input field for pincode

I am trying to create this input field for the user to register its pin, however I don't want to call another context screen. So, the point is simple, the user types the pin, the field clears, the text in the screen changes and the user types again , confirming the pin.
I ran into two problems tho. The field never clears, no matter what I do and when I click the field to type again the state resets back to the first pin input. here is the code for the widgets.
//Form fields
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Column(
children: [
Container(
width: 330,
child: pinCodeType == 1
? Text("Choose a Pincode",
style: TextStyle(color: brandBlue, fontSize: 18))
: Text("Repeat your Pincode",
style: TextStyle(color: brandBlue, fontSize: 18)),
),
Container(
height: 90,
width: 330,
child: pinCodeType == 1
? new PinCodeTextField(
enablePinAutofill: false,
keyboardAppearance: Brightness.dark,
length: 5,
obscureText: true,
textStyle: TextStyle(color: brandBlue),
animationType: AnimationType.scale,
keyboardType: TextInputType.numberWithOptions(),
autoDisposeControllers: true,
pinTheme: PinTheme(
shape: PinCodeFieldShape.underline,
//borderRadius: BorderRadius.circular(5),
fieldHeight: 80,
fieldWidth: 60,
activeColor: brandBlue,
inactiveFillColor: Colors.transparent,
inactiveColor: brandDarkGrey,
activeFillColor: brandWhite,
selectedColor: brandLightBlue,
selectedFillColor: Colors.transparent),
animationDuration: Duration(milliseconds: 300),
backgroundColor: brandWhite,
enableActiveFill: true,
errorAnimationController: errorController,
controller: textEditingController,
onCompleted: (v) {
if (pinCodeType == 1) {
pincode1 = v;
print("PINCODE 1 $pincode1");
print("PINCODE TYPE $pinCodeType");
setState(() {
textEditingController.clear();
pinCodeType = 2;
v = '';
});
}
},
onChanged: (value) {
print(value);
setState(() {});
},
beforeTextPaste: (text) {
print("Allowing to paste $text");
//if you return true then it will show the paste confirmation dialog. Otherwise if false, then nothing will happen.
//but you can show anything you want here, like your pop up saying wrong paste format or etc
return true;
},
appContext: context,
)
: new PinCodeTextField(
enablePinAutofill: false,
keyboardAppearance: Brightness.dark,
length: 5,
obscureText: true,
textStyle: TextStyle(color: brandBlue),
animationType: AnimationType.scale,
keyboardType: TextInputType.numberWithOptions(),
pinTheme: PinTheme(
shape: PinCodeFieldShape.underline,
//borderRadius: BorderRadius.circular(5),
fieldHeight: 80,
fieldWidth: 60,
activeColor: brandBlue,
inactiveFillColor: Colors.transparent,
inactiveColor: brandDarkGrey,
activeFillColor: brandWhite,
selectedColor: brandLightBlue,
selectedFillColor: Colors.transparent),
animationDuration: Duration(milliseconds: 300),
backgroundColor: brandWhite,
autoDisposeControllers: true,
enableActiveFill: true,
errorAnimationController: errorController2,
controller: textEditingController2,
onCompleted: (v) {
if (pinCodeType == 2) {
pincode1 = v;
print("PINCODE 2 $pincode2");
print("PINCODE TYPE $pinCodeType");
setState(() {
v = '';
pinCodeType++;
});
}
},
onChanged: (value) {
print(value);
setState(() {});
},
beforeTextPaste: (text) {
print("Allowing to paste $text");
//if you return true then it will show the paste confirmation dialog. Otherwise if false, then nothing will happen.
//but you can show anything you want here, like your pop up saying wrong paste format or etc
return true;
},
appContext: context,
)),
Container(
width: MediaQuery.of(context).size.width * 0.9,
child: ListTile(
title: Text(
"Use [biometric]",
style: TextStyle(color: brandBlue, fontSize: 18),
),
trailing: FlutterSwitch(
width: 70.0,
height: 30.0,
valueFontSize: 12.0,
toggleSize: 20.0,
value: biometricStatus,
activeText: "Yes",
activeTextColor: brandBlue,
inactiveText: "No",
activeColor: brandOrange,
borderRadius: 30.0,
padding: 8.0,
showOnOff: true,
onToggle: (val) {
setState(() {
biometricStatus = val;
});
},
),
)),
],
);
}),
And here is the code for the initial states
TextEditingController textEditingController = TextEditingController();
TextEditingController textEditingController2 = TextEditingController();
StreamController<ErrorAnimationType> errorController;
StreamController<ErrorAnimationType> errorController2;
bool hasError = false;
const brandBlue = const Color(0xff243665);
const brandWhite = const Color(0xffF8F8FA);
const brandLightGrey = const Color(0xffE7E9ED);
const brandMediumGrey = const Color(0xffAAB0B9);
const brandDarkGrey = const Color(0xff868E94);
const brandLightBlue = const Color(0xff0FAFDA);
const brandOrange = const Color(0xffEB684F);
bool biometricStatus = true;
String pincode1;
String pincode2;
var pinCodeType = 1;
#override
void initState() {
errorController = StreamController<ErrorAnimationType>();
textEditingController = TextEditingController();
textEditingController2 = TextEditingController();
pinCodeType = 1;
super.initState();
}
#override
void dispose() {
errorController.close();
super.dispose();
}
How do I get this right:?
You don't need to call textEditingController.clear(); inside setState() to clear the value set on the TextEditingController. Move the function outside setState and this should fix the issue.

How to check answers and change colors of radio buttons on right and wrong selection in flutter?

I am new in flutter app development. I have a issue in radio buttons. i have created a logic that works with flatButtons fine but i want to use this login with radio buttons. But my login gives me error that function name can't be assigned to function expressions.
Here is the image screenshot of error.
Material Button COde:
Widget choicebutton(String option, String k) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: MaterialButton(
// materialTapTargetSize: MaterialTapTargetSize.padded,
onPressed: () => checkanswer(k),
child: Text(
mydata[1][i.toString()][k],
// textDirection:TextDirection.ltr,
//textAlign: TextAlign.left,
style: TextStyle(
fontFamily: "Alike",
fontSize: 16.0,
color: Colors.white,
),
// maxLines: 1,
),
// padding: EdgeInsets.fromLTRB(2.0, 2.0, 50.0, 50.0),
color: btncolor[k],
splashColor: Colors.indigo[700],
highlightColor: Colors.indigo[700],
minWidth: 320.0,
height: 90.0,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
),
);
}
btncolor["a"] = Colors.indigo;
btncolor["b"] = Colors.indigo;
btncolor["c"] = Colors.indigo;
btncolor["d"] = Colors.indigo;
void checkanswer(String k) {
if (mydata[2][i.toString()] == mydata[1][i.toString()][k]) {
marks = marks + 1;
colortoshow = right;
} else {
colortoshow = wrong;
}
setState(() {
btncolor[k] = colortoshow;
canceltimer = true;
});
Timer(Duration(seconds: 1), nextquestion);
}
Widget Code:
Widget radioButton( k){
return RadioListTile(
value: 1,
groupValue: k ,
onChanged: (value){
checkanswer(k);
// btncolor[k];
},
title: Text(mydata[1][i.toString()][k],
style: TextStyle(
fontFamily: "Roboto",
fontSize: 18.0,
),
),
activeColor: btncolor[k],
);
}
Thanks in advance.
when passing functions as paramters you don't put the function name
For example
Widget radioBtn(){
return Radio(
value: null,
groupValue: null,
onChanged: (value){
},
);
}
If you however want to pass the function name, consider doing something like this
Widget radioBtn(){
return Radio(
value: null,
groupValue: null,
onChanged: whenRadioButtonChanges,
);
}
void whenRadioButtonChanges(value){
}
Hoep this helps you.