dart 未选中Flutter复选框,但执行onChanged:

wbrvyc0a  于 12个月前  发布在  Flutter
关注(0)|答案(1)|浏览(102)

我有一个检查框内的脚手架上 Flutter 的屏幕。当我点击它检查它,蓝色检查不显示。
onChanged:执行并且“value”为true。为什么会发生这种情况?

Widget build(BuildContext context) {

final _firestoreService = FirestoreService();
bool isChecked = false;

return Scaffold(
  appBar: CustomAppBar(),
  backgroundColor: Colors.white,
  body: SafeArea(
    child: SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: <Widget>[
            const Text(
              'User Profile',
              style: TextStyle(
                fontSize: 30,
              ),
            ),
            const SizedBox(
              height: 8.0,
            ),
            // Email entry text field
            TextField(
              controller: fNameController,
              keyboardType: TextInputType.text,
              textAlign: TextAlign.center,
              onChanged: (value) {
                ref.read(usersNotifierProvider.notifier).updatefName(value);
              },
              decoration: const InputDecoration(
                  hintText: 'First Name', labelText: 'First Name'),
            ),
            const SizedBox(
              height: 8.0,
            ),
            TextField(
              controller: lNameController,
              keyboardType: TextInputType.text,
              textAlign: TextAlign.center,
              onChanged: (value) {
                ref.read(usersNotifierProvider.notifier).updatelName(value);
              },
              decoration: const InputDecoration(
                  hintText: 'Last Name', labelText: 'Last Name'),
            ),
            const SizedBox(
              height: 8.0,
            ),
            StreamBuilder<QuerySnapshot>(
                // Get a list of available companies to assign the new user to a company
                stream: _db.collection('company').snapshots(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  List<DropdownMenuItem<String>> companyItems = [];
                  if (snapshot.hasData) {
                    final companyList = snapshot.data.docs;
                    for (var company in companyList) {
                      companyItems.add(
                        DropdownMenuItem(
                          value: company.id,
                          child: Text(
                            company['name'],
                          ),
                        ),
                      );
                    }
                  } else {
                    return const CircularProgressIndicator();
                  }
                  return DropdownButton<String>(
                    hint: const Text("Select Company"),
                    value: _selectedCompany,
                    onChanged: (companyValue) {
                      setState(() {
                        _selectedCompany = companyValue;
                        ref
                            .read(globalsNotifierProvider.notifier)
                            .updatecompanyId(companyValue!);
                      });
                    },
                    items: companyItems,
                  );
                }),
            const SizedBox(
              height: 8.0,
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const Text(
                  'Add a Company? ',
                  style: TextStyle(
                    color: Colors.blue,
                  ),
                ),
                Checkbox(
                  value: isChecked,
                  onChanged: (bool? value) {
                    setState(() {
                      isChecked = value!;
                    });
                  },
                ),
              ],
            ),
            const SizedBox(
              height: 8.0,
            ),
            TextField(
              controller: address1Controller,
              keyboardType: TextInputType.text,
              textAlign: TextAlign.center,
              onChanged: (value) {
                ref
                    .read(usersNotifierProvider.notifier)
                    .updateaddress1(value);
              },
              decoration: const InputDecoration(
                  hintText: 'Address 1', labelText: 'Address 1'),
            ),
            const SizedBox(
              height: 8.0,
            ),
            TextField(
              controller: address2Controller,
              textAlign: TextAlign.center,
              onChanged: (value) {
                ref
                    .read(usersNotifierProvider.notifier)
                    .updateaddress2(value);
              },
              decoration: const InputDecoration(
                  hintText: 'Address 2', labelText: 'Address 2'),
            ),
            const SizedBox(
              height: 8.0,
            ),
            TextField(
              controller: cityController,
              keyboardType: TextInputType.emailAddress,
              textAlign: TextAlign.center,
              onChanged: (value) {
                ref.read(usersNotifierProvider.notifier).updateCity(value);
              },
              decoration: const InputDecoration(
                  hintText: 'City', labelText: 'City'),
            ),
            const SizedBox(
              height: 8.0,
            ),
            DropdownButton(
              value: _currentUserState,
              items: _dropDownState,
              hint: const Text('Choose State'),
              onChanged: changedDropDownState,
            ),
            const SizedBox(
              height: 8.0,
            ),
            TextField(
              controller: zipController,
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              onChanged: (value) {
                ref
                    .read(usersNotifierProvider.notifier)
                    .updateZipcode(value);
              },
              decoration: const InputDecoration(
                  hintText: 'Zip Code', labelText: 'Zip Code'),
            ),
            const SizedBox(
              height: 8.0,
            ),
            TextField(
              inputFormatters: [maskFormatter],
              controller: cellPhoneController,
              keyboardType: TextInputType.phone,
              textAlign: TextAlign.center,
              onChanged: (value) {
                ref
                    .read(usersNotifierProvider.notifier)
                    .updateCellPhone(value);
              },
              decoration: const InputDecoration(
                  hintText: 'Cell Phone', labelText: 'Cell Phone'),
            ),
            const SizedBox(
              height: 8.0,
            ),
            TextField(
              inputFormatters: [maskFormatter],
              controller: officePhoneController,
              keyboardType: TextInputType.phone,
              textAlign: TextAlign.center,
              onChanged: (value) {
                ref
                    .read(usersNotifierProvider.notifier)
                    .updateOfficePhone(value);
              },
              decoration: const InputDecoration(
                  hintText: 'Office Phone', labelText: 'Office Phone'),
            ),
            const SizedBox(
              height: 8.0,
            ),
            StreamBuilder(
                stream: _db
                    .collection('mls')
                    .where('mlsState',
                        isEqualTo: ref
                            .read(globalsNotifierProvider)
                            .currentUserState)
                    .snapshots(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  List<DropdownMenuItem<String>> mlsItems = [];
                  if (snapshot.hasData) {
                    final mlsList = snapshot.data.docs;
                    for (var mls in mlsList) {
                      mlsItems.add(
                        DropdownMenuItem(
                          value: mls.id,
                          child: Text(
                            mls['mlsName'],
                          ),
                        ),
                      );
                    }
                  } else {
                    return const CircularProgressIndicator();
                  }
                  return DropdownButton<String>(
                    hint: const Text("Select MLS"),
                    value: _selectedMls,
                    onChanged: (mlsValue) {
                      setState(() {
                        _selectedMls = mlsValue;
                        ref
                            .read(globalsNotifierProvider.notifier)
                            .updatemlsId(mlsValue!);
                        ref
                            .read(usersNotifierProvider.notifier)
                            .updateMlsId(mlsValue);
                        ref
                            .read(usersNotifierProvider.notifier)
                            .updateMls(mlsValue);
                      });
                    },
                    items: mlsItems,
                  );
                }),
            const SizedBox(
              height: 8.0,
            ),
            RoundedButton(
              title: 'Save',
              colour: Colors.blueAccent,
              onPressed: () async {
                setState(() {
                  showSpinner = true;
                });
                try {
                  ref.read(usersNotifierProvider.notifier).saveUser(
                      //ref.read(companyNotifierProvider),
                      ref.read(globalsNotifierProvider),
                      ref.read(usersNotifierProvider));
                  ref
                      .read(globalsNotifierProvider.notifier)
                      .updatecurrentUserName(
                          '${fNameController.value.text} ${lNameController.value.text}');
                  ref
                      .read(globalsNotifierProvider.notifier)
                      .updatecurrentUserState(_currentUserState!);
                  await _firestoreService.saveDeviceToken(ref);
                  ref
                      .read(globalsNotifierProvider.notifier)
                      .updatetargetScreen(0);
                  if (isChecked) {
                    ref
                        .read(globalsNotifierProvider.notifier)
                        .updateAddCompany(false);
                    Navigator.of(context).pushReplacement(MaterialPageRoute(
                        builder: (context) => const CompanyScreen()));
                  } else {
                    Navigator.of(context).pushReplacement(MaterialPageRoute(
                        builder: (context) => MainScreen()));
                  }

                  setState(() {
                    showSpinner = false;
                  });
                } catch (e) {
                  // todo: add better error handling
                  //print(e);
                }
              },
            ),
            const SizedBox(
              height: 8.0,
            ),

            (widget != null)
                ? RoundedButton(
                    title: 'Delete',
                    colour: Colors.red,
                    onPressed: () async {
                      setState(() {
                        showSpinner = true;
                      });
                      try {
                        ref.read(usersNotifierProvider.notifier).deleteUser(
                            ref.watch(globalsNotifierProvider).currentUid);
                        ref
                            .read(globalsNotifierProvider.notifier)
                            .updatetargetScreen(2);
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => MainScreen()));
                        //Navigator.pushNamed(
                        //    context, AgentDashboardScreen.id);

                        setState(() {
                          showSpinner = false;
                        });
                      } catch (e) {
                        // todo: add better error handling
                        //print(e);
                      }
                    },
                  )
                : Container()
          ],
        ),
      ),
    ),
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: () async {
      setState(() {
        showSpinner = true;
      });
      try {
        ref.read(usersNotifierProvider.notifier).saveUser(
            //ref.read(companyNotifierProvider),
            ref.read(globalsNotifierProvider).companyId,
            ref.read(usersNotifierProvider).userId);
        ref.read(globalsNotifierProvider.notifier).updatetargetScreen(0);
        await _firestoreService.saveDeviceToken(ref);
        Navigator.push(
          context,
          new MaterialPageRoute(
            builder: (context) => MainScreen(),
          ),
        );
        setState(() {
          showSpinner = false;
        });
      } catch (e) {
        // todo: add better error handling
        print(e);
      }
    },
    backgroundColor: constants.kPrimaryColor,
    child: const Icon(
      Icons.assignment_turned_in_outlined,
      color: Colors.blueAccent,
    ),
  ),
);

字符串
}

**更新:**我在scaffold小部件中添加了整个代码块。我在onChange:中删除了ref.read(),但检查仍然没有显示。

u59ebvdq

u59ebvdq1#

这一行:

bool isChecked = false;

字符串
应该在构建方法之外;当您调用setState时,它将重新构建视图,它将再次调用构建方法,并且isState变量将始终为false。

相关问题