The state of my checkboxes keep returning to their original value in flutter - flutter

I have a profile page with some widgets which after saving and redrawing, they keep their new states, but my checkboxes do not, and I have not modified them at all. The new value is being saved on the database, but on the UI it's not preserved. If I turn the email checkbox to true, the 'true' boolean is saved, but it's not displayed on the frontend after pressing the submit button.
class _ProfilePageState extends State<ProfilePage> {
final _formKey = GlobalKey<FormState>();
bool? emailIsChecked = false;
bool? smsisChecked = false;
bool isTextFieldEnabled = false;
bool isIgnored = true;
bool isVisible = false;
bool editIsVisible = true;
bool emailIsEnabled = false;
bool smsIsEnabled = false;
bool nameEdit = false;
late TextEditingController countryController;
late TextEditingController languageController;
#override
void initState() {
super.initState();
countryController = TextEditingController(text: globals.signedInUser!.country);
languageController = TextEditingController(text: globals.signedInUser!.language);
selectedCountry = globals.signedInUser!.country;
selectedLanguage = globals.signedInUser!.language;
globals.signedInUser!.notifications.forEach(
(element) {
if ((element['type']) == 'Email') {
emailIsChecked = element['status'];
}
if ((element['type']) == 'SMS') {
smsisChecked = element['status'];
}
},
);
cleanInputStates();
}
#override
void dispose() {
countryController.dispose();
languageController.dispose();
super.dispose();
}
checkEditVisibility() {
if (editIsVisible == true) {
return true;
}
if (editIsVisible == false) {
return false;
}
}
checkEditAvailability() {
if (editIsVisible == false) {
return true;
}
if (editIsVisible == true) {
return false;
}
}
cleanInputStates() {
isTextFieldEnabled = false;
isIgnored = true;
editIsVisible = true;
isVisible = false;
smsIsEnabled = false;
emailIsEnabled = false;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
key: _formKey,
child: Row(
children: [
Flexible(
flex: 5,
child: Padding(
padding: const EdgeInsets.only(top: 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Visibility(
visible: editIsVisible,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green)),
icon: const Icon(Icons.edit),
label: Text('Edit'),
onPressed: () {
setState(() {
isTextFieldEnabled = true;
isIgnored = false;
isVisible = true;
editIsVisible = false;
smsIsEnabled = true;
emailIsEnabled = true;
});
}),
),
SizedBox(
width: 250,
)
],
),
SizedBox(
height: 30,
),
Flexible(
flex: 1,
child: Padding(
padding: const EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 20,
),
... // TextFieldInputs
Row(
children: [
Container(
child: Text(
"Country: ",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 22,
color: Colors.black.withOpacity(0.3),
),
),
),
SizedBox(
width: 100,
),
Container(
width: 300,
child: IgnorePointer(
ignoring: isIgnored,
child: DropdownButtonFormField2(
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
),
isExpanded: true,
hint: const Text(
'Select Your Country',
style: TextStyle(fontSize: 14),
),
icon: const Icon(
Icons.arrow_drop_down,
color: Colors.black45,
),
iconSize: 30,
buttonHeight: 60,
buttonPadding: const EdgeInsets.only(left: 20, right: 10),
dropdownDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
),
items: countryItems
.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
),
),
))
.toList(),
validator: (valueCountry) {
if (valueCountry == null) {
return 'Please select country.';
}
return null;
},
value: selectedCountry,
onChanged: (String? valueCountry) {
selectedCountry = valueCountry;
setState(() {
valueCountry;
});
},
),
),
),
// ),
],
),
SizedBox(
height: 20,
),
Row(
children: [
Container(
child: Text(
"Language: ",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 22,
color: Colors.black.withOpacity(0.3),
),
),
),
SizedBox(
width: 80,
),
Container(
width: 300,
child: IgnorePointer(
ignoring: isIgnored,
child: DropdownButtonFormField2(
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
),
isExpanded: true,
hint: const Text(
'Select Your Language',
style: TextStyle(fontSize: 14),
),
icon: const Icon(
Icons.arrow_drop_down,
color: Colors.black45,
),
iconSize: 30,
buttonHeight: 60,
buttonPadding: const EdgeInsets.only(left: 20, right: 10),
dropdownDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
),
items: languageItems
.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
),
),
))
.toList(),
value: selectedLanguage,
validator: (valueLanguage) {
if (valueLanguage == null) {
return 'Please select language.';
}
return null;
},
onChanged: (String? valueLanguage) {
selectedLanguage = valueLanguage;
setState(() {
valueLanguage;
});
},
),
),
),
// ),
],
),
Row()
],
),
SizedBox(
width: 120,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
child: Row(
children: [
Text(
"Receive notifications by: ",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 22,
color: Colors.black.withOpacity(0.3),
),
),
],
),
),
],
),
SizedBox(
height: 10,
),
Row(
children: [
Container(
width: 300,
child: CheckboxListTile(
enabled: emailIsEnabled,
title: Text("E-mail"),
value: emailIsChecked,
onChanged: (bool? newEmailValue) {
setState(() {
emailIsChecked = newEmailValue;
});
},
activeColor: Colors.green,
),
),
],
),
Row(
children: [
Container(
width: 300,
child: CheckboxListTile(
enabled: smsIsEnabled,
title: Text("SMS"),
value: smsisChecked,
onChanged: (bool? newSmsValue) {
setState(() {
smsisChecked = newSmsValue;
});
},
activeColor: Colors.green,
),
),
],
),
SizedBox(
height: 100,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Visibility(
visible: isVisible,
child: Row(
children: <Widget>[
ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red)),
onPressed: () {
setState(() {
cleanInputStates();
_formKey.currentState!.reset();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfilePage()));
});
print("Cleaning states");
},
child: Text("Dismiss"),
),
SizedBox(
width: 100,
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.green)),
onPressed: () {
if (_formKey.currentState!.validate()) {
final userInfo = {
"_id": globals.signedInUser!.userId,
"firstName": firstnameTextController.text,
"lastName": lastnameTextController.text,
"email": emailTextController.text,
"phoneNumber": phoneNumberTextController.text,
"country": selectedCountry.toString(),
"language": selectedLanguage.toString(),
"notifications": [
{"type": "Email", "status": emailIsChecked},
{"type": "SMS", "status": smsisChecked}
]
};
globals.socketController.updateUser(userInfo);
Fluttertoast.showToast(
msg: "Applying changes.", // message
toastLength: Toast.LENGTH_LONG, // length
gravity: ToastGravity.BOTTOM_RIGHT, // location
timeInSecForIosWeb: 2,
webBgColor: "#4caf50",
);
}
print("DATA IS BEING SAVED");
setState(() {
if (_formKey.currentState!.validate()) {
globals.signedInUser!.email =
emailTextController.text;
globals.signedInUser!.phoneNumber =
phoneNumberTextController.text;
globals.signedInUser!.firstName =
firstnameTextController.text;
globals.signedInUser!.lastName =
lastnameTextController.text;
globals.signedInUser!.country =
selectedCountry as String;
globals.signedInUser!.language =
selectedLanguage as String;
cleanInputStates();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfilePage()));
} else {
print("ingresando else");
}
});
},
child: Text("Save"),
),
],
),
)
],
)
],
),
],
),
),
),
],
), //Column ends here
),
),
],
),
),
);
}
}

Update: After some testings and workarounds, I found that the second issue was due to not assigning a new value prior to returning to the initState. To do that, I added the following code segment into the setState() of the submit button, which is the fetch of the notification parameters within the initState() but assigning the new checkbox values into the array. Additionally, I removed the cleanInputStates(); on the initState as #Paulo mentioned and everything else kept the same.
globals.signedInUser!.notifications.forEach(
(element) {
if ((element['type']) == 'Email') {
element['status'] = emailIsChecked;
}
if ((element['type']) == 'SMS') {
element['status'] = smsisChecked;
}
},
);

Related

Why is my flutter widgets not working when in a different state management

I bought an online template app and i am trying to hardcode my email and password credentials in my flutter frontend because i don't have access to the backend api yet to change from email/password auth to phone auth, so i want to force code the logic into my flutter widget.
This means i am trying to implement the onPressed: () { controller.login(); }, function on a login button to get me to the home screen with my customized widget.
The original code given to me works fine when i hardcode the credentials in the text form field but when i hardcode the text form field in my customized widget and use same onPressed: () { controller.login(); }, function it don't work.
I want to know if it's because of i'm in a different state management or there's something i'm failing to do.
I will give the original code and my customized UI code in the snippets for comparison.
PS: i even tried to use same text form field in my widget but hide it with Visibility() in flutter. When i use Visibility() in the original code, onPressed: () { controller.login(); }, works but when i use it in my customized widget, it doest.
How do work around this? If you need more clarification, i am willing to offer. Thanks.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../../common/helper.dart';
import '../../../../../common/ui.dart';
import '../../../../models/setting_model.dart';
import '../../../../routes/app_routes.dart';
import '../../../../services/settings_service.dart';
import '../../../global_widgets/block_button_widget.dart';
import '../../../global_widgets/circular_loading_widget.dart';
import '../../../global_widgets/text_field_widget.dart';
import '../../controllers/auth_controller.dart';
class LoginView extends GetView<AuthController> {
final Setting _settings = Get.find<SettingsService>().setting.value;
#override
Widget build(BuildContext context) {
controller.loginFormKey = new GlobalKey<FormState>();
return Visibility(
visible: false,
child: WillPopScope(
onWillPop: Helper().onWillPop,
child: Scaffold(
appBar: AppBar(
title: Text(
"Login".tr,
style: Get.textTheme.headline6
.merge(TextStyle(color: context.theme.primaryColor)),
),
centerTitle: true,
backgroundColor: Get.theme.colorScheme.secondary,
automaticallyImplyLeading: false,
elevation: 0,
),
body: Form(
key: controller.loginFormKey,
child: ListView(
primary: true,
children: [
Stack(
alignment: AlignmentDirectional.bottomCenter,
children: [
Container(
height: 180,
width: Get.width,
decoration: BoxDecoration(
color: Get.theme.colorScheme.secondary,
borderRadius:
BorderRadius.vertical(bottom: Radius.circular(10)),
boxShadow: [
BoxShadow(
color: Get.theme.focusColor.withOpacity(0.2),
blurRadius: 10,
offset: Offset(0, 5)),
],
),
margin: EdgeInsets.only(bottom: 50),
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
children: [
Text(
_settings.salonAppName,
style: Get.textTheme.headline6.merge(TextStyle(
color: Get.theme.primaryColor, fontSize: 24)),
),
SizedBox(height: 5),
Text(
"Welcome to the best salon service system!".tr,
style: Get.textTheme.caption.merge(
TextStyle(color: Get.theme.primaryColor)),
textAlign: TextAlign.center,
),
// Text("Fill the following credentials to login your account", style: Get.textTheme.caption.merge(TextStyle(color: Get.theme.primaryColor))),
],
),
),
),
Container(
decoration: Ui.getBoxDecoration(
radius: 14,
border:
Border.all(width: 5, color: Get.theme.primaryColor),
),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Image.asset(
'assets/icon/icon.png',
fit: BoxFit.cover,
width: 100,
height: 100,
),
),
),
],
),
Obx(() {
if (controller.loading.isTrue)
return CircularLoadingWidget(height: 300);
else {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Visibility(
visible: false,
maintainState: true,
child: TextFieldWidget(
labelText: "Email Address".tr,
hintText: "johndoe#gmail.com".tr,
initialValue: 'salon#demo.com',
onSaved: (input) =>
controller.currentUser.value.email = input,
validator: (input) => !input.contains('#')
? "Should be a valid email".tr
: null,
iconData: Icons.alternate_email,
),
),
Obx(() {
return Visibility(
visible: false,
maintainState: true,
child: TextFieldWidget(
labelText: "Password".tr,
hintText: "••••••••••••".tr,
initialValue: '123456',
onSaved: (input) =>
controller.currentUser.value.password = input,
validator: (input) => input.length < 3
? "Should be more than 3 characters".tr
: null,
),
);
}),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {
Get.toNamed(Routes.FORGOT_PASSWORD);
},
child: Text("Forgot Password?".tr),
),
],
).paddingSymmetric(horizontal: 20),
BlockButtonWidget(
onPressed: () {
controller.login();
},
color: Get.theme.colorScheme.secondary,
text: Text(
"Login".tr,
style: Get.textTheme.headline6.merge(
TextStyle(color: Get.theme.primaryColor)),
),
).paddingSymmetric(vertical: 10, horizontal: 20),
TextButton(
onPressed: () {
//Get.toNamed(Routes.REGISTER);
},
child: Text("You don't have an account?".tr),
).paddingOnly(top: 20),
GestureDetector(
onTap: () {
Get.toNamed(Routes.SETTINGS_LANGUAGE);
},
child: Text(
Get.locale.toString().tr,
textAlign: TextAlign.center,
),
),
],
);
}
}),
],
),
),
),
),
);
}
}
THIS IS THE ORIGINAL WIDGET CODE
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../routes/app_routes.dart';
import '../../../global_widgets/circular_loading_widget.dart';
import '../../../global_widgets/text_field_widget.dart';
import '../../controllers/auth_controller.dart';
import 'login_view.dart';
import 'pin_number.dart';
import 'keyboard_number.dart';
class PinScreen extends StatefulWidget {
const PinScreen({Key key}) : super(key: key);
#override
State<PinScreen> createState() => _PinScreenState();
}
class _PinScreenState extends State<PinScreen> {
List<String> currentPin = ["", "", "", ""];
TextEditingController pinOneController = TextEditingController();
TextEditingController pinTwoController = TextEditingController();
TextEditingController pinThreeController = TextEditingController();
TextEditingController pinFourController = TextEditingController();
var outlineInputBorder = OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(color: Colors.transparent),
);
int pinIndex = 0;
#override
Widget build(BuildContext context) {
final controller = Get.find<AuthController>();
controller.loginFormKey = new GlobalKey<FormState>();
return Form(
key: controller.loginFormKey,
child: SafeArea(
child: Column(
children: [
buildExitButton(),
Obx(() {
if (controller.loading.isTrue)
return CircularLoadingWidget(height: 300);
else {
return Expanded(
child: Container(
alignment: Alignment(0, 0.5),
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
buildSecurityText(),
SizedBox(height: 20.0),
buildPinRow(),
SizedBox(height: 10.0),
buildNumberPad(),
SizedBox(height: 20.0),
Visibility(
visible: false,
maintainState: true,
child: TextFieldWidget(
labelText: "Email Address".tr,
hintText: "johndoe#gmail.com".tr,
initialValue: 'salon#demo.com',
validator: (input) => !input.contains('#')
? "Should be a valid email".tr
: null,
iconData: Icons.alternate_email,
),
),
Obx(() {
return Visibility(
visible: false,
maintainState: true,
child: TextFieldWidget(
labelText: "Password".tr,
hintText: "••••••••••••".tr,
initialValue: '123456',
validator: (input) => input.length < 3
? "Should be more than 3 characters".tr
: null,
iconData: Icons.lock_outline,
keyboardType: TextInputType.visiblePassword,
suffixIcon: IconButton(
onPressed: () {
controller.hidePassword.value =
!controller.hidePassword.value;
},
color: Theme.of(context).focusColor,
icon: Icon(controller.hidePassword.value
? Icons.visibility_outlined
: Icons.visibility_off_outlined),
),
),
);
}),
Container(
child: new RichText(
text: new TextSpan(
children: [
new TextSpan(
recognizer: TapGestureRecognizer()
..onTap = () {
// Get.toNamed(Routes.REGISTER);
},
text: 'Forgot Pin ?',
style: new TextStyle(
color: Color(0xff3498DB),
fontSize: 14,
fontWeight: FontWeight.w500),
),
],
),
),
),
SizedBox(height: 20.0),
MaterialButton(
onPressed: () {
controller.login();
},
color: Color(0xff34495E),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.18),
),
padding: EdgeInsets.symmetric(
horizontal: 30, vertical: 10),
minWidth: double.infinity,
child: Text(
'Next',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600),
),
),
SizedBox(height: 32.0),
],
),
),
);
}
})
],
),
),
);
}
buildNumberPad() {
return Expanded(
child: Container(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
KeyboardNumber(
n: 1,
onPressed: () {
pinIndexSetup("1");
},
),
KeyboardNumber(
n: 2,
onPressed: () {
pinIndexSetup("2");
},
),
KeyboardNumber(
n: 3,
onPressed: () {
pinIndexSetup("3");
},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
KeyboardNumber(
n: 4,
onPressed: () {
pinIndexSetup("4");
},
),
KeyboardNumber(
n: 5,
onPressed: () {
pinIndexSetup("5");
},
),
KeyboardNumber(
n: 6,
onPressed: () {
pinIndexSetup("6");
},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
KeyboardNumber(
n: 7,
onPressed: () {
pinIndexSetup("7");
},
),
KeyboardNumber(
n: 8,
onPressed: () {
pinIndexSetup("8");
},
),
KeyboardNumber(
n: 9,
onPressed: () {
pinIndexSetup("9");
},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 60.0,
child: MaterialButton(
onPressed: null,
child: SizedBox(),
),
),
KeyboardNumber(
n: 0,
onPressed: () {
pinIndexSetup("0");
},
),
Container(
width: 60.0,
child: MaterialButton(
onPressed: () {
clearPin();
},
height: 60.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(60.0),
),
child: Image.asset(
'assets/icon/clear-symbol.png',
),
),
)
],
),
],
),
),
),
);
}
clearPin() {
if (pinIndex == 0)
pinIndex = 0;
else if (pinIndex == 4) {
setPin(pinIndex, "");
currentPin[pinIndex - 1] = "";
pinIndex--;
} else {
setPin(pinIndex, "");
currentPin[pinIndex - 1] = "";
pinIndex--;
}
}
pinIndexSetup(String text) {
if (pinIndex == 0)
pinIndex = 1;
else if (pinIndex < 4) pinIndex++;
setPin(pinIndex, text);
currentPin[pinIndex - 1] = text;
String strPin = "";
currentPin.forEach((e) {
strPin += e;
});
if (pinIndex == 4) print(strPin);
}
setPin(int n, String text) {
switch (n) {
case 1:
pinOneController.text = text;
break;
case 2:
pinTwoController.text = text;
break;
case 3:
pinThreeController.text = text;
break;
case 4:
pinFourController.text = text;
break;
}
}
buildExitButton() {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: MaterialButton(
onPressed: () {
Navigator.pop(context);
},
height: 50.0,
minWidth: 50.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
child: Icon(
Icons.clear,
color: Colors.black54,
),
),
),
],
);
}
buildSecurityText() {
return Column(
children: [
Align(
alignment: Alignment.topLeft,
child: Text(
'Enter PIN',
style: TextStyle(
color: Color(0xff151515),
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(
height: 12,
),
Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(right: 80),
child: Text(
'Enter 4 digit PIN to access your account ',
style: TextStyle(
color: Color(0xff151515),
fontSize: 14,
fontWeight: FontWeight.w500,
fontStyle: FontStyle.normal,
),
),
),
),
],
);
}
buildPinRow() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
PINNumber(
outlineInputBorder: outlineInputBorder,
textEditingController: pinOneController,
),
PINNumber(
outlineInputBorder: outlineInputBorder,
textEditingController: pinTwoController,
),
PINNumber(
outlineInputBorder: outlineInputBorder,
textEditingController: pinThreeController,
),
PINNumber(
outlineInputBorder: outlineInputBorder,
textEditingController: pinFourController,
),
],
);
}
}
THIS IS MY CUSTOMIZED WIDGET TREE/CODE

Fill width in single datacell in flutter

I'm trying to accomplished something like had been issued here : Flutter single `DataCell` color
I want to grey out the cell to let user know that was supposed to leave blank. Currently I manage to fill the height of datacell but the width.
my code snippet:
_data[i][newColumn] = Container(
width: double.infinity,
height: double.infinity,
color: Colors.grey,
child: Text(''));
Result: Last cell at the most right which fill up height space only:
full code :
import 'dart:convert';
import 'dart:ui';
import 'package:http/http.dart';
import 'package:flutter/material.dart';
class InspectionSheet extends StatefulWidget {
const InspectionSheet({Key? key}) : super(key: key);
#override
State<InspectionSheet> createState() => _InspectionSheetState();
}
class _InspectionSheetState extends State<InspectionSheet> {
GlobalKey<FormState> _formKey = new GlobalKey();
bool validate = false;
TextEditingController ctrlsampleSize = TextEditingController();
final List<Map<String, dynamic>> _data = [
{
//"checkitemID": "0",
"Ballooning No": "1",
"Datatype": "1",
"Specifications": ".325+-0.020",
"Tool": "CALIPER",
"LSL": "0.305",
"Target": "2",
"USL": "0.325",
"Tol-": "0.02",
"Tol+": "0.02",
"Image": "",
"WI": ""
},
{
//"checkitemID": "0",
"Ballooning No": "2",
"Datatype": "2",
"Specifications": ".325+-0.020",
"Tool": "CALIPER",
"LSL": "0.305",
"Target": "2",
"USL": "0.325",
"Tol-": "0.02",
"Tol+": "0.02",
"Image": "",
"WI": ""
},
];
late List<String> _columnNames;
//String _selectedValue = inputList.first;
String _selectedValue = 'PASS';
void startbutton() {
validateEmpty();
if (_formKey.currentState!.validate()) {
addDataCol();
}
}
void validateEmpty() {
//if (_formKey.currentState!.validate()) {
// // If the form is valid, display a snackbar. In the real world,
// // you'd often call a server or save the information in a database.
// ScaffoldMessenger.of(context).showSnackBar(
// const SnackBar(content: Text('Processing Data')),
// );
ctrlsampleSize.text.isEmpty ? validate = false : validate = true;
//}
}
void addDataCol() {
int colNo = int.parse(ctrlsampleSize.text);
if (colNo < 1) {
return;
}
setState(() {
for (var i = 1; i <= colNo; i++) {
_addColumn('Data $i');
}
});
}
void _addColumn(String newColumn) {
if (_columnNames.contains(newColumn)) {
return;
}
setState(() {
for (var i = 0; i <= _data.length - 1; i++) {
if (_data[i]['Datatype'] == '1') {
_data[i][newColumn] = TextFormField();
} else if (_data[i]['Datatype'] == '2') {
_data[i][newColumn] = DropdownButton<String>(
value: _selectedValue,
icon: const Icon(Icons.arrow_drop_down_circle_outlined),
elevation: 16,
underline: Container(
height: 2,
color: Colors.blue,
),
onChanged: (newValue) {
setState(() {
_selectedValue = newValue!;
});
},
items:
// inputList.map<DropdownMenuItem<String>>((String value) {
// return DropdownMenuItem<String>(
// value: value,
// child: Text(value),
// onTap: () {
// _selectedValue = value;
// },
// );
// }).toList(),
[
DropdownMenuItem(
value: 'PASS',
child: const Text('PASS'),
onTap: () {
_selectedValue = 'PASS';
},
),
DropdownMenuItem(
value: 'FAIL',
child: const Text('FAIL'),
onTap: () {
_selectedValue = 'FAIL';
},
),
DropdownMenuItem(
value: 'UAI',
child: const Text('UAI'),
onTap: () {
_selectedValue = 'UAI';
},
),
DropdownMenuItem(
value: 'NA',
child: const Text('NA'),
onTap: () {
_selectedValue = 'NA';
},
)
]);
} else if (_data[i]['Datatype'] == '3') {
if (newColumn == 'Data 1') {
_data[i][newColumn] = TextButton(
onPressed: () {
_displayTextInputDialog(context);
},
child: const Text('-'));
} else {
_data[i][newColumn] = Container(
width: double.infinity,
height: double.infinity,
color: Colors.grey,
child: Text(''));
}
} else {
_data[i][newColumn] = TextButton(
onPressed: () {
_displayTextInputDialog(context);
},
child: const Text('-'));
}
}
_columnNames.add(newColumn);
});
}
#override
void initState() {
dateInput.text = "";
_columnNames = _data[0].keys.toList();
//set the initial value of text field
super.initState();
//// Start listening to changes.
ctrlsampleSize.addListener(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
Form(
child: Row(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: 210,
child: Form(
key: _formKey,
child: ListView(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 200,
height: 200,
child: Column(
children: <Widget>[
TextFormField(
controller: ctrlsampleSize,
validator: ((value) {
if (value == null || value.isEmpty) {
return 'Please enter sample size';
}
return null;
}),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(0, 5, 0, 0),
child: Container(
width: 400,
height: 200,
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
image: DecorationImage(
image: AssetImage('images/Test1.jpg'),
fit: BoxFit.fill,
)),
),
),
],
),
],
),
),
Container(
child: Container(
child: Center(
child: Row(
// add Column
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(15, 15, 860, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
Text(
"Total Parameter : 6",
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(15, 15, 8, 0),
child: ElevatedButton(
onPressed: () => startbutton(),
child: const Text('Start'),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(15, 15, 8, 0),
child: ElevatedButton(
onPressed: () {},
child: const Text('Reset'),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(15, 15, 8, 0),
child: ElevatedButton(
onPressed: () {},
child: const Text('Save'),
),
),
],
),
),
)),
Padding(
padding: const EdgeInsets.all(8.0),
child:
//****uncomment if use Provider */
// Container(
// decoration: BoxDecoration(
// border: Border.all(color: Colors.black),
// ),
// child: ConstrainedBox(
// constraints: const BoxConstraints(
// maxHeight: 600,
// maxWidth: 813,
// ),
// child: Column(
// children: [
// Expanded(
// child: ChangeNotifierProvider<CheckItemProvider>(
// create: (context) => CheckItemProvider(),
// child: Consumer<CheckItemProvider>(
// builder: (context, provider, child) {
// provider.getData(context);
// return const Center(
// child: CircularProgressIndicator());
// // when we have the json loaded... let's put the data into a data table widget
// return
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: DataTable(
headingRowHeight: 30,
border: TableBorder.all(
color: Colors.grey,
),
headingRowColor: MaterialStateColor.resolveWith(
(states) => Colors.lightBlue),
headingTextStyle: const TextStyle(
color: Colors.white, fontWeight: FontWeight.w800),
columns: _columnNames.map((columnName) {
return DataColumn(
label: Text(
columnName,
// style: const TextStyle(
// fontSize: 18,
// fontWeight: FontWeight.w600,
// ),
),
);
}).toList(),
rows:
_data // Loops through dataColumnText, each iteration assigning the value to element
.map((row) {
return DataRow(
cells: row.values.map((cellValue) {
try {
return DataCell(
cellValue,
onTap: () {},
);
} catch (e) {
return DataCell(Text(cellValue));
}
;
}).toList());
}).toList(),
),
),
),
//},
// ),
// ),
// ),
// ],
// ),
// ),
// ),
),
],
),
);
}
}

How to usage Obx() with getx in flutter?

On my UI screen, I have 2 textfields in a column. If textFormFieldEntr is empty, hide textFormFiel. If there is a value in the textFormFieldEntr, let the other textfield be visible. After I set the bool active variable to false in the Controller class, I checked the value in the textFormFieldEntr in the showText class. I'm wrong using obx on the UI screen. The textfields are listed in the _formTextField method. Can you answer by explaining the correct obx usage on the code I shared?
class WordController extends GetxController {
TextEditingController controllerInput1 = TextEditingController();
TextEditingController controllerInput2 = TextEditingController();
bool active = false.obs();
final translator = GoogleTranslator();
RxList data = [].obs;
#override
void onInit() {
getir();
super.onInit();
}
void showText() {
if (!controllerInput1.text.isEmpty) {
active = true;
}
}
ekle(Word word) async {
var val = await WordRepo().add(word);
showDilog("Kayıt Başarılı");
update();
return val;
}
updateWord(Word word) async {
var val = await WordRepo().update(word);
showDilog("Kayıt Başarılı");
return val;
}
deleteWord(int? id) async {
var val = await WordRepo().deleteById(id!);
return val;
}
getir() async {
//here read all data from database
data.value = await WordRepo().getAll();
print(data);
return data;
}
translateLanguage(String newValue) async {
if (newValue == null || newValue.length == 0) {
return;
}
List list = ["I", "i"];
if (newValue.length == 1 && !list.contains(newValue)) {
return;
}
var translate = await translator.translate(newValue, from: 'en', to: 'tr');
controllerInput2.text = translate.toString();
//addNote();
return translate;
}
showDilog(String message) {
Get.defaultDialog(title: "Bilgi", middleText: message);
}
addNote() async {
var word =
Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
await ekle(word);
getir();
clear();
}
clear() {
controllerInput2.clear();
controllerInput1.clear();
}
updateNote() async {
var word =
Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
await updateWord(word);
await getir();
update();
}
}
UI:
class MainPage extends StatelessWidget {
bool _active=false.obs();
String _firstLanguage = "English";
String _secondLanguage = "Turkish";
WordController controller = Get.put(WordController());
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
controller.getir();
return Scaffold(
drawer: _drawer,
backgroundColor: Colors.blueAccent,
appBar: _appbar,
body: _bodyScaffold,
floatingActionButton: _floattingActionButton,
);
}
SingleChildScrollView get _bodyScaffold {
return SingleChildScrollView(
child: Column(
children: [
chooseLanguage,
translateTextView,
],
),
);
}
AppBar get _appbar {
return AppBar(
backgroundColor: Colors.blueAccent,
centerTitle: true,
title: Text("TRANSLATE"),
elevation: 0.0,
);
}
get chooseLanguage => Container(
height: 55.0,
decoration: buildBoxDecoration,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
firstChooseLanguage,
changeLanguageButton,
secondChooseLanguage,
],
),
);
get buildBoxDecoration {
return BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(
width: 3.5,
color: Colors.grey,
),
),
);
}
refreshList() {
controller.getir();
}
get changeLanguageButton {
return Material(
color: Colors.white,
child: IconButton(
icon: Icon(
Icons.wifi_protected_setup_rounded,
color: Colors.indigo,
size: 30.0,
),
onPressed: () {},
),
);
}
get secondChooseLanguage {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Center(
child: Text(
this._secondLanguage,
style: TextStyle(
color: Colors.blue[600],
fontSize: 22.0,
),
),
),
),
),
);
}
get firstChooseLanguage {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Center(
child: Text(
this._firstLanguage,
style: TextStyle(
color: Colors.blue[600],
fontSize: 22.0,
),
),
),
),
),
);
}
get translateTextView => Column(
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 2.0),
child: _formTextField,
),
Container(
height: Get.height/1.6,
child: Obx(() {
return ListView.builder(
itemCount: controller.data.length,
itemBuilder: (context, index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 0.8),
child: Container(
color: Colors.white30,
height: 70.0,
padding:
EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
firstText(controller.data, index),
secondText(controller.data, index),
],
),
historyIconbutton,
],
),
),
);
},
);
}),
)
],
);
get _formTextField {
return Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
color: Colors.white30,
height: 120.0,
padding: EdgeInsets.only(left: 16.0, top: 8.0, bottom: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
textFormFieldEntr,
favoriIconButton,
],
),
),
textFormField //burası kapandı
],
),
);
}
get textFormFieldEntr {
return Flexible(
child: Container(
child: TextFormField(
onTap: () {
showMaterialBanner();
},
// onChanged: (text) {
// controller.translateLanguage(text);
// },
controller: controller.controllerInput1,
maxLines: 6,
validator: (controllerInput1) {
if (controllerInput1!.isEmpty) {
return "lütfen bir değer giriniz";
} else if (controllerInput1.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
hintText: "Enter",
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
),
);
}
void showMaterialBanner() {
ScaffoldMessenger.of(Get.context!).showMaterialBanner(MaterialBanner(
backgroundColor: Colors.red,
content: Padding(
padding: const EdgeInsets.only(top: 30.0),
child: Column(
children: [
TextFormField(
controller: controller.controllerInput1,
maxLines: 6,
onChanged: (text) {
controller.translateLanguage(text);
controller.showText();
},
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
suffixIcon: IconButton(onPressed: () {
FocusScope.of(Get.context!).unfocus();
closeBanner();
}, icon: Icon(Icons.clear),),
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
SizedBox(height: 80.0),
TextFormField(
controller: controller.controllerInput2,
maxLines: 6,
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
],
),
),
actions: [
IconButton(
onPressed: () {
closeBanner();
},
icon: Icon(
Icons.arrow_forward_outlined,
color: Colors.indigo,
size: 36,
),
),
]));
}
void closeBanner() {
ScaffoldMessenger.of(Get.context!).hideCurrentMaterialBanner();
}
// } controller.controllerInput1.text==""?_active=false: _active=true;
get textFormField {
return Visibility(
visible: controller.active,
child: Container(
color: Colors.white30,
height: 120.0,
padding: EdgeInsets.only(left: 16.0, right: 42.0, top: 8.0, bottom: 8.0),
child: Container(
child: TextFormField(
controller: controller.controllerInput2,
maxLines: 6,
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
),
),
);
}
FutureBuilder<dynamic> get historyWordList {
return FutureBuilder(
future: controller.getir(),
builder: (context, AsyncSnapshot snapShot) {
if (snapShot.hasData) {
var wordList = snapShot.data;
return ListView.builder(
itemCount: wordList.length,
itemBuilder: (context, index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
margin: EdgeInsets.only(left: 8.0, right: 8.0, top: 0.8),
child: Container(
color: Colors.white30,
height: 70.0,
padding: EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
firstText(wordList, index),
secondText(wordList, index),
],
),
historyIconbutton,
],
),
),
);
},
);
} else {
return Center();
}
},
);
}
IconButton get historyIconbutton {
return IconButton(
onPressed: () {},
icon: Icon(Icons.history),
iconSize: 30.0,
);
}
Text firstText(wordList, int index) {
return Text(
"İngilizce: ${wordList[index].wordEn ?? ""}",
style: TextStyle(
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
Text secondText(wordList, int index) {
return Text(
"Türkçe: ${wordList[index].wordTr ?? ""}",
style: TextStyle(
fontWeight: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
get favoriIconButton {
return IconButton(
alignment: Alignment.topRight,
onPressed: () async {
bool validatorKontrol = _formKey.currentState!.validate();
if (validatorKontrol) {
String val1 = controller.controllerInput1.text;
String val2 = controller.controllerInput2.text;
print("$val1 $val2");
await controller.addNote();
await refreshList();
}
await Obx(() => textFormField(
controller: controller.controllerInput2,
));
await Obx(() => textFormField(
controller: controller.controllerInput1,
));
},
icon: Icon(
Icons.forward,
color: Colors.blueGrey,
size: 36.0,
),
);
}
FloatingActionButton get _floattingActionButton {
return FloatingActionButton(
onPressed: () {
Get.to(WordListPage());
},
child: Icon(
Icons.app_registration,
size: 30,
),
);
}
Drawer get _drawer {
return Drawer(
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
userAccountsDrawerHeader,
drawerFavorilerim,
drawersettings,
drawerContacts,
],
),
);
}
ListTile get drawerContacts {
return ListTile(
leading: Icon(Icons.contacts),
title: Text("Contact Us"),
onTap: () {
Get.back();
},
);
}
ListTile get drawersettings {
return ListTile(
leading: Icon(Icons.settings),
title: Text("Settings"),
onTap: () {
Get.back();
},
);
}
ListTile get drawerFavorilerim {
return ListTile(
leading: Icon(
Icons.star,
color: Colors.yellow,
),
title: Text("Favorilerim"),
onTap: () {
Get.to(FavoriListPage());
},
);
}
UserAccountsDrawerHeader get userAccountsDrawerHeader {
return UserAccountsDrawerHeader(
accountName: Text("UserName"),
accountEmail: Text("E-mail"),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.grey,
child: Text(
"",
style: TextStyle(fontSize: 40.0),
),
),
);
}
}
You can simple do it like this
class ControllerSample extends GetxController{
final active = false.obs
functionPass(){
active(!active.value);
}
}
on page
final sampleController = Get.put(ControllerSample());
Obx(
()=> Form(
key: yourkeyState,
child: Column(
children: [
TextFormField(
//some other needed
//put the function on onChanged
onChanged:(value){
if(value.isEmpty){
sampleController.functionPass();
}else{
sampleController.functionPass();
}
}
),
Visibility(
visible: sampleController.active.value,
child: TextFormField(
//some other info
)
),
]
)
)
)

The State of Selected value keeps being reverted back to it's original value

I want the value of selected to be of the changed one, but everytime I navigate to a different page then come back it keeps returning selected = true
. I tried putting the late bool selected; then initializing in the initState() but it still doesn't work.
bool selected = true;
#override
Widget build(BuildContext context) {
var why = DateTime.parse(
"${DateTime.now().toString().substring(0, 10)} ${widget.time}");
return Container(
padding: EdgeInsets.all(10),
height: 100,
decoration: BoxDecoration(
color: Color(0xFFF9F9FB),
borderRadius: BorderRadius.circular(30),
),
child: Row(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 15,
),
Center(
child: Text(
"${widget.time}",
style: TextStyle(fontWeight: FontWeight.bold),
),
)
],
),
SizedBox(
width: 50,
),
Container(
height: 100,
width: 1,
color: Colors.grey.withOpacity(0.5),
),
SizedBox(
width: 10,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("${widget.module}"),
Row(
children: [
Icon(
Icons.location_on,
color: Colors.grey,
size: 20,
),
SizedBox(
width: 3,
),
Text(
"${widget.loc}",
style: TextStyle(
color: Colors.grey,
fontSize: 13,
),
),
],
),
Row(
children: [
Icon(
Icons.person,
color: Colors.grey,
),
SizedBox(
width: 1,
),
Text(
"${widget.lecturer}",
style: TextStyle(
color: Colors.grey,
fontSize: 13,
),
),
],
)
],
),
),
IconButton(
icon: Icon(selected
? Icons.notifications_none
: Icons.notifications_active),
onPressed: () async {
// print(why);
print(widget.time);
print(widget.module);
print(widget.id);
setState(() {
selected = !selected;
});
if (selected == false) {
displayNotification("${widget.module}", why, widget.id);
} else if (selected == true) {
localNotification.cancel(widget.id);
}
},
),
],
),
);
}
Future<void> displayNotification(
String lesson, DateTime lessonTime, int id) async {
FlutterLocalNotificationsPlugin().zonedSchedule(
id,
lesson,
"${lesson} ",
tz.TZDateTime.from(lessonTime, tz.local),
NotificationDetails(
android: AndroidNotificationDetails(
"channel id", "channel name", "channel Description"),
),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true);
}
}
void initializeSetting() async {
var initializeAndroid = AndroidInitializationSettings("#mipmap/ic_launcher");
var initializeSetting = InitializationSettings(android: initializeAndroid);
await localNotification.initialize(initializeSetting);
}
A quick fix :-
Just place your selected variable outside any class like this.
import ...//all the import statements
bool selected = true;
//Rest other code

How to Get the Number of Pages in Pageview to be used in a line indicator in Flutter?

May i ask for help on how to get the number of pages inside a pageview,
similar to listview you can get the number of list via listview.length, but for pageview there is no pageview.length property that i can use,
i tried using pageview.builder but i couldnt initiate the data as a list showig an issue that i need to initiate it as an initializers?,
please help me figure it out
i need the data inside the pageview to be used inside the _lineprogressindicator, to show how many are the questionaires inside to make an indicator
here is my code
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:survey/content/thankyou.dart';
import 'package:survey/widgets/animations.dart';
import 'package:survey/widgets/buttonstyle.dart';
import 'package:survey/widgets/widgetlist.dart';
class questionaires extends StatefulWidget {
#override
_questionairesState createState() => _questionairesState();
}
class _questionairesState extends State<questionaires> {
TextStyle conqueststyle = TextStyle(
fontSize: 15, fontWeight: FontWeight.bold, color: Colors.indigo);
TextStyle questionstyle = TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
);
String titletop = 'Post Visit Patient Satisfaction';
String q1 = "Sample Question HERE";
String q2 = "Sample Question HERE";
String q3 = "Sample Question HERE";
String q4 = "Sample Question HERE";
int percentagenum = 0;
int _currValue = 1;
bool _loading;
double _progress;
final _texteditingcontroller = TextEditingController();
final _pageController = PageController(initialPage: 0, keepPage: true);
var _currentpage = 0;
List answernumbers = ["5", "4", "3", "2", "1"];
List currentselectedvalue = [];
List usingCollection1 = [
"Excellent",
"Very Good",
"Good",
"Fair",
"Poor",
];
#override
void dispose() {
super.dispose();
_texteditingcontroller.dispose();
_loading = false;
_progress = 0.0;
percentagenum = 0;
_currValue = 0;
usingTimes1 = '';
usingTimes = '';
usingTimes2 = '';
}
void initState() {
super.initState();
usingTimes1 = '';
usingTimes = '';
usingTimes2 = '';
_loading = false;
_progress = 0.0;
percentagenum = 0;
_texteditingcontroller.clear();
_currValue = 0;
}
void pageChanged(int index) {
setState(() {
_currentpage = index;
});
}
void _selectedanswers(data1, data2) {
if (_progress.toStringAsFixed(1) == '1.0') {
print(data1);
print(data2);
_texteditingcontroller.text;
}
}
void _updateProgress() {
setState(() {
_progress += 0.25;
percentagenum += 25;
if (_progress.toStringAsFixed(1) == '1.0') {
_loading = false;
_progress = 0;
percentagenum = 0;
Navigator.push(context, FadeRoute(page: thankyou()));
return;
}
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomPadding: false,
body: Padding(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: 100,
height: 60,
child: Image.asset(imgtit),
),
Stack(
children: <Widget>[
Container(
child: Text(
titletop,
style: conqueststyle,
maxLines: 1,
),
),
_buildPageView(),
_lineprogressindicator()
],
)
],
),
),
),
);
}
_buildPageView() {
return Container(
height: MediaQuery.of(context).size.height / 1.25,
child: PageView(
controller: _pageController,
onPageChanged: (index) {
pageChanged(index);
},
children: <Widget>[
_emojiquestions(q1),
_selectedutton(q2),
_numberrating(q3),
_textboxquestion(q4),
],
));
}
_lineprogressindicator() {
return Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: Column(
children: <Widget>[
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(50.0),
),
color: Colors.indigo,
onPressed: () {
_pageController.nextPage(
duration: kTabScrollDuration, curve: Curves.ease);
_loading = !_loading;
_updateProgress();
},
child: Icon(
Icons.check,
color: Colors.white,
size: 50,
),
),
SizedBox(
height: 10,
),
Text('%$percentagenum'),
LinearProgressIndicator(
value: _progress,
),
],
),
);
}
_emojiquestions(String quest1) {
final using = usingCollection1[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Question 1',
style: conqueststyle,
textAlign: TextAlign.right,
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration.collapsed(hintText: quest1),
maxLines: 5,
style: conqueststyle,
),
Expanded(
child: Center(
child: Container(
height: 300,
child: ListView.separated(
separatorBuilder: (context, index) => SizedBox(height: 10),
itemCount: usingCollection1.length,
itemBuilder: (context, index) => GestureDetector(
onTapUp: (index) {
_selectedanswers(index, null);
},
child: Card(
color: usingTimes == usingCollection1[index]
? Colors.blue.withAlpha(100)
: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(
height: 50,
width: 70,
child: Image.asset(emojiimage[index]),
),
Text(usingCollection1[index])
],
),
Divider(
height: index < usingCollection1.length ? 1.0 : 0.0,
),
],
),
),
),
)),
),
)
],
);
}
_selectedutton(String quest1) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Question 1',
style: conqueststyle,
textAlign: TextAlign.right,
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration.collapsed(hintText: quest1),
maxLines: 5,
style: conqueststyle,
),
Expanded(
child: Center(
child: Container(
height: 300,
child: Column(
children: List.generate(usingCollection1.length, (int index) {
final using = usingCollection1[index];
return GestureDetector(
onTap: () {
setState(() {
_currValue = index;
_selectedanswers(index, null);
usingTimes = using.identifier;
});
},
child: Card(
color: usingTimes == using.identifier
? Colors.blue.withAlpha(100)
: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Radio(
value: index,
groupValue: _currValue,
onChanged: (val) =>
setState(() => _currValue = val),
),
Text(using.displayContent)
],
),
Divider(
height:
index < usingCollection1.length ? 1.0 : 0.0,
),
],
),
));
}),
),
),
),
)
],
);
}
_numberrating(quest) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Question 2',
style: conqueststyle,
textAlign: TextAlign.right,
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration.collapsed(hintText: quest),
maxLines: 5,
style: conqueststyle,
),
Text("**5 is the highest"),
Container(
height: MediaQuery.of(context).size.height / 12.0,
width: MediaQuery.of(context).size.width,
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: usingCollection1.length,
itemBuilder: (context, index) {
final using = usingCollection1[index];
return GestureDetector(
onTapUp: (index) {
setState(() {
_selectedanswers(null, index);
usingTimes = using.identifier;
});
},
child: Card(
color: usingTimes == using.identifier
? Colors.blue.withAlpha(100)
: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
side: BorderSide(color: Colors.indigoAccent)),
child: Column(
children: <Widget>[
SizedBox(
height: 50,
width: 50,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
answernumbers[index],
textAlign: TextAlign.center,
style: conqueststyle,
),
],
)),
),
],
),
),
);
},
),
)
],
);
}
_textboxquestion(quest) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Question 2',
style: conqueststyle,
textAlign: TextAlign.right,
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration.collapsed(hintText: quest),
maxLines: 5,
style: conqueststyle,
),
TextFormField(
decoration: InputDecoration(
hintText: "Your FeedBack Here",
border: OutlineInputBorder(),
),
controller: _texteditingcontroller,
maxLines: 7,
style: conqueststyle,
)
],
);
}
}
For your case were the number of elements is known beforehand, I would suggest that you store your pages in a local variable and then call length on it. A small snippet would look something like this:
class MyState extends State<MyWidget> {
List<Widget> _pages = [
Container(color: Colors.blue,),
Container(color: Colors.amber,),
];
#override
Widget build(BuildContext context) {
return MyComplexWidgetTree(
child: PageView(
controller: PageController(),
children: _pages,
),
);
}
void _myMethodThatRequiresNumberOfPages() {
int numberOfPages = pages.length;
}
}