0

Field validation does not work, an error is displayed: Null check operator used on a null value. I took an example from docs.flutter. How can I solve this?

class _AddGroupPageState extends State<AddGroupPage> {
  final _groupController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  @override
  void dispose() {
    _groupController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return: Scaffold(
    body: Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        children: [
          TextFormField(
            key: _formKey,
            controller: _groupController,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Group name cannot be empty';
              }
              return null;
            },
          ),
        ],
      ),
    ),
    ...

void _saveGroup() {
  final isValid = _formKey.currentState!.validate();
  if (isValid) {
    BlocProvider.of<NewGroupBloc>(context)
        .add(AddGroupEvent(_groupController.text.trim()));
  }
}

2
  • 1
    how did you initilize _formKey? Commented Jun 3, 2022 at 12:36
  • i updated the example Commented Jun 3, 2022 at 12:40

2 Answers 2

1

Wrap your TextFormField with Form widget and pass the formkey to that widget

 Form(
          key: _formKey,
          child: TextFormField(
            controller: _groupController,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Group name cannot be empty';
              }
              return null;
            },
          ),
        ),
Sign up to request clarification or add additional context in comments.

Comments

1

You have to give formKey to forms not textfield itself Use like this:

                    Form(
                    key: _formKey,
                    child: Column(
                      children: [
                        TextFormField(
                        
                        //your code

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.