我的复选框的状态在flutter中不断返回到它们的初始值

nr9pn0ug  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(144)

我有一个个人资料页面,其中的一些小部件在保存和重绘后,保持了它们的新状态,但我的复选框没有,而且我根本没有修改它们。新值被保存在数据库中,但在UI上它没有被保存。如果我把电子邮件复选框设置为true,“true”布尔值被保存,但在按下提交按钮后它不会显示在前端。

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
              ),
            ),
          ],
        ),
      ),
    );
  }
}
wpx232ag

wpx232ag1#

更新:经过一些测试和解决方法,我发现第二个问题是由于在返回initState之前没有分配新值。为此,我将以下代码段添加到提交按钮的setState()中,这是在initState()中获取通知参数,但将新的复选框值分配到数组中。此外,我删除了cleanInputStates();正如@Paulo提到的那样,其他一切都保持不变。

globals.signedInUser!.notifications.forEach(
      (element) {
        if ((element['type']) == 'Email') {
           element['status'] = emailIsChecked;
        }
        if ((element['type']) == 'SMS') {
           element['status'] = smsisChecked;
        }
      },
    );

相关问题