Home > Back-end >  Dart Null safety error : Null check operator used on a null value
Dart Null safety error : Null check operator used on a null value

Time:12-07

I got this error, i understood it but i don't know how to fix it This error occurs when I try to use the variables of the 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)]),
            ),
          ],
        ),
      ),
    );
    }

here is the 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)))
            ],
          )
        ],
      ),
    );
  }
}

I don't have more details thanks in advance! I am listening to you, be indulgent I am a beginner thank you!

error code

════════ Exception caught by widgets library ═══════════════════════════════════ The following _CastError was thrown building MyDrawerPages(dirty, state: _MyDrawerPagesState#a6f02): Null check operator used on a null value

CodePudding user response:

This error is caused When Null check operator (!) is used on variable with a null value.

You must track all the variable and find this null value or use other operator to solve the problem or check if the value is not null. You can use ?? operator and give an alternative value if null like this

Text(name ?? 'Not Found')

     

You can find every thing you need about null aware operators in this article Go To Article

CodePudding user response:

the problem is here

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

you're trying to access name and team where they are supposed to be not null, because they are marked late, but you don't assign them a value until you click on the ok button, which in the build method above they are null.

so you should make them nullable and check wether they are null or not instead. like this:

String? name;
String? team;

...

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

try this and tell me if it worked!

  • Related