Home > Blockchain >  How to solve the error: Null check operator used on a null value?
How to solve the error: Null check operator used on a null value?

Time:06-03

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()));
  }
}

CodePudding user response:

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;
            },
          ),
        ),

CodePudding user response:

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

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