Null Related Error - The argument type 'String? Function(String)' can't be assigned to the parameter type 'String? Function(String?)?'

Viewed 853

The same code works in the tutorial video, not sure what is happening here. I think this is related to null safety.

I did try applying ? in this solution, but I was not able to reach a solution that works. When I apply the ? method, the validation wont' work.

How to solve this issue and build the project.

This is what I get when I run the solution enter image description here

This is the video URL having this sample https://youtu.be/nFSL-CqwRDo enter image description here


This is my full code

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  //const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Coding with Curry',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: FormScreen(),
    );
  }
}

class FormScreen extends StatefulWidget {
  //FormScreen({Key key}) : super(key: key);

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

class _FormScreenState extends State<FormScreen> {
  String _name = "";

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Widget _buildName() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Name'),
      validator: (String value) {
        if (value.isEmpty) {
          return "Name is Requried";
        }
      },
      onSaved: (String value){
        _name = value;
      },
    );
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Form Demo"),
        ),
        body: Container(
          margin: EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildName(),
                SizedBox(
                  height: 100,
                ),
                RaisedButton(
                    child: Text(
                      "Submit",
                      style: TextStyle(color: Colors.blue, fontSize: 16),
                    ),
                    onPressed: () => {
                      if(!_formKey.currentState.validate()){
                        return;
                      }

                      _formKey.currentState.save();

                    })
              ],
            ),
          ),
        ));
  }
}

When I apply the null in the solution, I am not able to write the validation code enter image description here

2 Answers

When you use the ? symbol you are saying that the variable can be null, so you can just check if it's null first, eg:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  //const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Coding with Curry',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: FormScreen(),
    );
  }
}

class FormScreen extends StatefulWidget {
  //FormScreen({Key key}) : super(key: key);

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

class _FormScreenState extends State<FormScreen> {
  String _name = "";

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Widget _buildName() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Name'),
      validator: (String? value) {
        if (value == null || value.isEmpty) {
          return "Name is Requried";
        }
      },
      onSaved: (String? value){
        _name = value!;
      },
    );
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Form Demo"),
        ),
        body: Container(
          margin: EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildName(),
                SizedBox(
                  height: 100,
                ),
                RaisedButton(
                    child: Text(
                      "Submit",
                      style: TextStyle(color: Colors.blue, fontSize: 16),
                    ),
                    onPressed: () {
                      if(_formKey.currentState!.validate()){
                        return _formKey.currentState!.save();
                      }
                    })
              ],
            ),
          ),
        ));
  }
}

The exclamation mark (eg, _name = value!;) tells the compiler that you know this nullable variable is never null. You'll see a runtime error if it actually is null.

You might also find this interesting: https://flutter.dev/docs/cookbook/forms/validation

Error:

You get the error because validator expects a function with the parameter type nullable string (String?) but you're passing it as non-nullable string (String). For example:

TextFormField(
  validator: (String value) {}, // Error
)

Solution:

The fix is to either provide String? or just omit the string.

TextFormField(
  validator: (String? value) {}, // No error
)

or

TextFormField(
  validator: (value) {}, // No error
)
Related