Home > OS >  Null check operator used on a null value even when the value is not null
Null check operator used on a null value even when the value is not null

Time:01-02

I can't insert my data inside my database even when I have already used controller. It still shows this error

The following _CastError was thrown while handling a gesture: Null check operator used on a null value

Here is my code:

import 'package:flutter/material.dart';
import 'package:testerlogin/models/flowerbook.dart';
import 'package:testerlogin/models/user.dart';
import '../common_widgets/buttons.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import '../common_widgets/checkbox.dart';

class FormPage extends StatefulWidget {
  const FormPage({Key? key, required this.user}) : super(key: key);
  final User user;
  @override
  State<FormPage> createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {
  final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();
  String selectedValue = 'Bouquet';

  final dateController = TextEditingController();
  final checkboxController = TextEditingController();
  final dropdownController = TextEditingController();

  final TextStyle labelStyle = const TextStyle(
    fontFamily: 'Poppins',
    fontWeight: FontWeight.w500,
  );

  final TextStyle inputStyle = const TextStyle(
    fontFamily: 'Poppins',
    fontWeight: FontWeight.w600,
  );

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      body: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: SafeArea(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                //Spacing
                const SizedBox(
                  height: 25,
                ),

                //Back Button
                Container(
                  height: 50,
                  padding: const EdgeInsets.fromLTRB(2 * 16, 0, 2 * 16, 0),
                  width: double.infinity,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      IconButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        icon: const Icon(Icons.arrow_back),
                      ),
                    ],
                  ),
                ),

                const SizedBox(
                  height: 25,
                ),

                SizedBox(
                  width: screenWidth,
                  child: Padding(
                    padding:
                        const EdgeInsets.fromLTRB(3 * 16, 0, 3 * 16, 3 * 16),
                    child: Column(
                      children: [
                        //Checkbox

                        FormField(builder: (FormFieldState state) {
                          return InputDecorator(
                              decoration: InputDecoration(
                                labelText: "Delivery Date",
                                labelStyle: labelStyle,
                                errorText: state.errorText,
                                border: const OutlineInputBorder(),
                                floatingLabelBehavior:
                                    FloatingLabelBehavior.always,
                              ),
                              child: FormBuilderDateTimePicker(
                                controller: dateController,
                                name: "delivery_date",
                              ));
                        }),

                        const SizedBox(height: 25),

                        FormField(
                          builder: (FormFieldState state) {
                            return InputDecorator(
                              decoration: InputDecoration(
                                labelText: "Flower Type",
                                labelStyle: labelStyle,
                                errorText: state.errorText,
                                border: const OutlineInputBorder(),
                                floatingLabelBehavior:
                                    FloatingLabelBehavior.always,
                              ),
                              child: Column(
                                children: <Widget>[
                                  checkItemBuilder(context, "Roses",
                                      checkboxController: checkboxController),
                                  checkItemBuilder(context, "Tulips",
                                      checkboxController: checkboxController),
                                  checkItemBuilder(context, "Carnation",
                                      checkboxController: checkboxController),
                                  checkItemBuilder(context, "Daisies",
                                      checkboxController: checkboxController),
                                  checkItemBuilder(context, "Tulips",
                                      checkboxController: checkboxController),
                                ],
                              ),
                            );
                          },
                        ),

                        const SizedBox(height: 25),

                        SizedBox(
                          width: MediaQuery.of(context).size.width,
                          child: FormField(
                            builder: (FormFieldState state) {
                              return InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Arrangement",
                                  labelStyle: labelStyle,
                                  errorText: state.errorText,
                                  border: const OutlineInputBorder(),
                                  floatingLabelBehavior:
                                      FloatingLabelBehavior.always,
                                ),
                                child: DropdownButton<String>(
                                  value: selectedValue,
                                  isExpanded: true,
                                  onChanged: (String? newValue) {
                                    setState(() {
                                      selectedValue = newValue ?? 'Bouquet';
                                      dropdownController.text = selectedValue;
                                    });
                                  },
                                  items: <String>[
                                    'Bouquet',
                                    'Vase',
                                    'Box',
                                    'Basket'
                                  ].map<DropdownMenuItem<String>>(
                                      (String value) {
                                    return DropdownMenuItem<String>(
                                      value: value,
                                      child: Text(value),
                                    );
                                  }).toList(),
                                ),
                              );
                            },
                          ),
                        ),

                        const SizedBox(height: 25),

                        //Submit Button
                        ButtonGradient(
                          label: 'Submit',
                          textStyle: const TextStyle(
                            fontFamily: 'Poppins',
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                          borderRadius: 50,
                          gradientColor: const [
                            Colors.purpleAccent,
                            Colors.deepPurple,
                          ],
                          onPressed: () {
                            if (_formKey.currentState!.validate()) {
                              Flowerbook flowerbook = Flowerbook(
                                deliver_date: dateController.text,
                                flower_type: checkboxController.text,
                                arrangement: dropdownController.text,
                                user_id: widget.user.user_id,
                              );

                              Flowerbook.register(flowerbook);
                            }
                          },
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

I think something is wrong around here:

 onPressed: () {
                            if (_formKey.currentState!.validate()) {
                              Flowerbook flowerbook = Flowerbook(
                                deliver_date: dateController.text,
                                flower_type: checkboxController.text,
                                arrangement: dropdownController.text,
                                user_id: widget.user.user_id,
                              );

                              Flowerbook.register(flowerbook);
                            }

But it could also be at the widgets

Here is the error:

The following _CastError was thrown while handling a gesture:
Null check operator used on a null value

When the exception was thrown, this was the stack:
#0      _FormPageState.build.<anonymous closure> (package:testerlogin/pages/formpage.dart:187:54)
#1      _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21)
#2      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:253:24)
#3      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:627:11)
#4      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:306:5)
#5      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:276:7)
#6      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:163:27)
#7      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:464:20)
#8      GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:440:22)
#9      RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:337:11)
#10     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:395:7)
#11     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:357:5)
#12     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:314:7)
#13     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:295:7)
#14     _invoke1 (dart:ui/hooks.dart:167:13)
#15     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:341:7)
#16     _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)

Handler: "onTap"
Recognizer:
  TapGestureRecognizer#75718

That cannot be possible because all of the values are already inside the controller.

I tried printing out the data when I pressed submit button. But it still shows the same error, it didn't even print out the values inside the controller. So, I have removed the code. And tried other ways to fix this.

The code should insert the values to the database after the user have filled in the form.

CodePudding user response:

as mentioned inthe error, on line 187

if (_formKey.currentState!.validate()) {

you're using currentState! (Null Check Operator) when (evidently) currentState is null. I dont know why, but you can confirm by checking this, and handling the null case accordingly, or checking the rest of the code to see why it is null in this case.

CodePudding user response:

You should change the Form widget that is a child of SingleChildScrollView to FormBuilder.

check README on flutter_form_builder package

  • Related