繁体   English   中英

Dart Null 安全错误:Null 检查运算符用于 Z37A6259CC0C1DAE29BDZA7866489DFF0 值

[英]Dart Null safety error : Null check operator used on a null value

我收到了这个错误,我明白了,但我不知道如何解决这个错误当我尝试使用profilPicker class 的变量时发生这个错误。

class MyDrawerPages extends StatefulWidget {
    final ValueChanged<DrawerItem> onSelectedItem;
    final VoidCallback? onClick;
    const MyDrawerPages({
    Key? key,
    required this.onSelectedItem,
    this.onClick,
    }) : super(key: key);

    @override
    _MyDrawerPagesState createState() => _MyDrawerPagesState();
     }

    class _MyDrawerPagesState extends State<MyDrawerPages> {
    final signUpKey = GlobalKey<_ProfilPickerState>();
    var stringName = '';
     var stringTeam = '';

     @override
     Widget build(BuildContext context) {
    
      final name = signUpKey.currentState!.name;
      final team = signUpKey.currentState!.team;
      final bool isSignin = signUpKey.currentState!.isSignin;

    return Scaffold(
      body: Container(
        color: const Color(0xFFE26A2C),
        child: Column(
          children: [
            Padding(
              key: signUpKey,
              padding: const EdgeInsets.only(top: 20, bottom: 10),
              child: ListTile(
                leading: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, '/profil_picker');
                  },
                  child: const CircleAvatar(
                    backgroundColor: Color(0xFF463E3E),
                    child: Icon(
                      Icons.person,
                      size: 40,
                      color: Colors.white,
                    ),
                    radius: 22,
                  ),
                ),
                title: Text(
                  isSignin ? name.toString().toUpperCase() : stringName,
                  style: const TextStyle(color: Colors.white),
                ),
                subtitle: Text(
                    isSignin
                        ? team.toString()
                        : stringTeam,
                    style: const TextStyle(color: Colors.white)),
              ),
            ),
            SingleChildScrollView(
              child: Column(children: [listTileDrawer(context)]),
            ),
          ],
        ),
      ),
    );
    }

这是ProfilPicker class


class _ProfilPickerState extends State<ProfilPicker> {
  bool visible = false;
  File? image;

  late String name;
  late String team;
  TextEditingController nameController = TextEditingController();
  TextEditingController teamController = TextEditingController();

  var isSignin = true;

  Future pickeImage(ImageSource source) async {
    final image = await ImagePicker().pickImage(source: source);
    if (image == null) return;

    final saveImage = await saveImagepermanently(image.path);

    try {
      setState(() {
        this.image = saveImage;
      });
    } on Exception catch (e) {
      // ignore: avoid_print
      print('failed to pick image $e');
    }
  }

  bool signUp = true;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          iconTheme: const IconThemeData(color: Colors.black),
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        backgroundColor: const Color(0xFFFFFFFF),
        body: Center(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Column(
                  children: [
                    Container(
                      height: 150,
                      width: 150,
                      decoration: BoxDecoration(
                          color: Colors.blueGrey[200],
                          borderRadius: BorderRadius.circular(200)),
                      child: image != null
                          ? ClipOval(
                              child: Image.file(
                                image!,
                                width: 150,
                                height: 150,
                                fit: BoxFit.cover,
                              ),
                            )
                          : const Icon(
                              Icons.add_a_photo,
                              size: 30,
                            ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 100,
                ),
                signUp
                    ? Column(
                        children: [
                          Card(
                              margin:
                                  const EdgeInsets.symmetric(horizontal: 40),
                              child: ListTile(
                                onTap: () {
                                  setState(() {
                                    pickeImage(ImageSource.gallery);
                                    signUp = false;
                                  });
                                },
                                leading: const Icon(Icons.image_outlined),
                                title: const Text("Gallery"),
                              ),
                              color: Colors.blue[100]),
                          const SizedBox(
                            height: 10,
                          ),
                          Card(
                            color: Colors.blue[100],
                            margin: const EdgeInsets.symmetric(horizontal: 40),
                            child: ListTile(
                              onTap: () {
                                setState(() {
                                  pickeImage(ImageSource.camera);
                                  signUp = false;
                                });
                              },
                              leading: const Icon(Icons.camera),
                              title: const Text("Camera"),
                            ),
                          ),
                        ],
                      )
                    : Column(
                        children: [
                          _listTileBuilder(),
                          const SizedBox(
                            height: 30,
                          )
                        ],
                      )
              ],
            ),
          ),
        ),
      ),
    );
  }

  _listTileBuilder() {
    return SingleChildScrollView(
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Padding(
            padding: const EdgeInsets.all(10),
            child: Column(
              children: [
                Container(
                    alignment: Alignment.topLeft,
                    padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                    child: const Text('Profil')),
                const Padding(
                  padding: EdgeInsets.only(right: 50),
                  child: Divider(
                    indent: 4,
                    color: Colors.black,
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(10),
            child: Column(
              children: [
                TextField(
                  controller: nameController,
                  maxLines: 1,
                  keyboardType: TextInputType.name,
                  style: const TextStyle(fontSize: 14),
                  decoration: InputDecoration(
                    filled: true,
                    fillColor: Colors.blue[100],
                    border: const OutlineInputBorder(
                        borderSide: BorderSide.none,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    label: const Text('name',
                        style: TextStyle(fontStyle: FontStyle.italic)),
                  ),
                ),
                const Padding(padding: EdgeInsets.all(4)),
                TextField(
                  controller: teamController,
                  maxLines: 1,
                  keyboardType: TextInputType.name,
                  style: const TextStyle(fontSize: 14),
                  decoration: InputDecoration(
                    filled: true,
                    fillColor: Colors.blue[100],
                    border: const OutlineInputBorder(
                        borderSide: BorderSide.none,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    label: const Text(
                      'Team',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                )
              ],
            ),
          ),
          const Padding(
            padding: EdgeInsets.all(20),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TextButton(
                  onPressed: () {
                    // Navigator.pop();
                  },
                  child: Text(
                    'cancel'.toUpperCase(),
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  )),
              TextButton(
                  onPressed: () {
                    setState(() {
                      isSignin;
                      name = nameController.text;
                      team = teamController.text;
                    });
                  },
                  child: Text('ok'.toUpperCase(),
                      style: const TextStyle(fontWeight: FontWeight.bold)))
            ],
          )
        ],
      ),
    );
  }
}

我没有更多细节提前谢谢,我在听你的,放纵我是初学者谢谢!

错误代码

════════ 小部件库捕获的异常═════════════════════════════␕══以下_CastError 被抛出构建 MyDrawerPages(dirty, state: _MyDrawerPagesState#a6f02): Null 检查运算符用于 Z37A6259CC0C1DAE299A7866489DFF 值

当 Null 检查运算符 ( ! ) 用于具有 null 值的变量时,会导致此错误。

您必须跟踪所有变量并找到此 null 值或使用其他运算符解决问题或检查该值是否不是 null。 您可以使用?? 如果 null 像这样,运算符并给出一个替代值

Text(name ?? 'Not Found')

     

您可以在本文Go中找到有关 null 感知运算符所需的一切

问题就在这里

final name = signUpKey.currentState!.name;
final team = signUpKey.currentState!.team;

您正在尝试访问他们应该不是 null 的名称和团队,因为它们被标记为late ,但是在单击 ok 按钮之前您不会为它们分配值,在上面的构建方法中它们是 null .

所以你应该让它们为空并检查它们是否是 null 或不是。 像这样:

String? name;
String? team;

...

final name = signUpKey.currentState!.name ?? ''; 
final team = signUpKey.currentState!.team ?? '';

试试这个,告诉我它是否有效!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM