skip to Main Content

Here is a screenshot of the code
Screen shot of my code

I want my defaultFormField to take two optional parameters,

  • Function() onSubmit, to be used as an argument for the "onFieldSubmitted" if needed

  • Function() onChange, to be used as an argument for the "onChanged" if needed

**The first problem is that I’m forced to use the "required" statement for both parameters **

**The second problem is that even after I use the "required" statement I still can’t use the parameters as arguments **

In the course I’m watching, the instructor doesn’t face any problems doing just that, here is a screenshot of their code
Screenshot of instructor’s code

I was wondering if this is just a problem with the flutter version I’m using so I need to go back to an older version, or is there a problem with my code that I need to change.

I also tried to make the parameters nullable like this
Screenshot of the nullable fix

but I still can’t use them in my code,

I haven’t tried switching back to an older version of flutter, because I think it will be a hassle and I don’t know how.

Thanks in advance

2

Answers


  1. As you guessed, the code from the instructor’s screenshot compiles only because it predates null-safe Dart.

    Your attempt for the "nullable fix" didn’t work because the type still didn’t match: you need ValueChanged<String>? (which is void Function(String value)), not just Function?.

    Login or Signup to reply.
  2. Yeah, the instructor’s code is in the old version of dart lang which was without null safety, and now they added null safety.

    And the function onSubmitted and onChanged are nullable so you need to make the parameter’s declaration accordingly.

    So use the below function, here i have mentioned the detailed type of the both the functions. A easy way to get the accurate type is to hover on the parameter and see what type of data it’s expecting and use that(it may differ as per IDEs, you can checks the docs too).

      Widget defaultFormField(
          {required TextEditingController controller,
          required TextInputType type,
          required void Function(String?)? onSubmit,
          required void Function(String?)? onChange}) =>
      TextFormField(
        controller: controller,
        keyboardType: type,
        onChanged: onChange,
        onFieldSubmitted: onSubmit,
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search