Closure call with mismatched arguments: function '_RegisterState.build.<anonymous closure>' Receiver: Closure: (String) => Null

Viewed 935

I don't know why this error happens the full error is :

Closure call with mismatched arguments: function '_RegisterState.build.<anonymous closure>'
Receiver: Closure: (String) => Null
Tried calling: _RegisterState.build.<anonymous closure>()
Found: _RegisterState.build.<anonymous closure>(String) => Null

I think the error in the reusable Textformfield that I created any way its code here my reusable TextformField code is :

import 'package:flutter/material.dart';
import '../constants.dart';

class CustomTextField extends StatelessWidget {
const CustomTextField(
  {Key? key, required this.hint, required this.icon, required this.onClick})
  : super(key: key);
final String hint;
final IconData icon;
final Function? onClick;

final OutlineInputBorder border = const OutlineInputBorder(
  borderRadius: BorderRadius.all(Radius.circular(20)),
  borderSide: BorderSide(color: Colors.white));

@override
Widget build(BuildContext context) {
return Padding(
  padding: const EdgeInsets.symmetric(horizontal: 30),
  child: TextFormField(
    onSaved: onClick!(),
    validator: (value) {
      if (value!.isEmpty) {
        switch (hint) {
          case 'Enter your email':
            return 'Enter your Email';
          case 'Enter your Name':
            return 'Enter a name';
          case 'Enter your password':
            return 'Enter a password';
          default:
            return 'Enter a value';
        }
      }
      if (hint == 'Enter your email' && !value.contains('@')) {
        return 'Enter valid email';
      }
      if (hint == 'Enter your Name' && value.length < 3) {
        return 'Enter valid Name';
      }
      if (hint == 'Enter your password' && value.length < 5) {
        return 'your password is weak';
      }
    },
    obscureText: hint == 'Enter your password' ? true : false,
    cursorColor: kMainColor,
    decoration: InputDecoration(
      hintText: hint,
      prefixIcon: Icon(
        icon,
        color: kMainColor,
      ),
      filled: true,
      fillColor: kSecondaryColor,
      focusedBorder: border,
      enabledBorder: border,
      border: border,
      ),
      ),
      );
      }
      }

I used it in 2 screens to login and register

my register screen code is :

import 'package:e_commerce/screens/login_screen.dart';
import 'package:e_commerce/servises/auth.dart';
import 'package:e_commerce/widgets/custom_input_field.dart';
import 'package:flutter/material.dart';

import '../constants.dart';

class Register extends StatefulWidget {
static String routName = 'Register';
const Register({Key? key}) : super(key: key);

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

class _RegisterState extends State<Register> {
String? name;
String? email;
String? password;
final GlobalKey<FormState> _key = GlobalKey();
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
return Scaffold(
  backgroundColor: kMainColor,
  body: SingleChildScrollView(
    child: Container(
      padding: const EdgeInsets.only(top: 100),
      alignment: Alignment.center,
      child: Form(
        key: _key,
        child: Column(
          children: [
            Image.asset("assets/images/icons/cart.png"),
            const Text('Buy now',
                style: TextStyle(
                    fontFamily: 'Corinthia',
                    color: Colors.black,
                    fontSize: 40,
                    fontWeight: FontWeight.bold)),
            SizedBox(
              height: height * 0.05,
            ),
            CustomTextField(
                onClick: (String value) {
                  if (_key.currentState!.validate()) {
                    name = value;
                  }
                },
                hint: 'Enter your Name',
                icon: Icons.person),
            SizedBox(
              height: height * 0.02,
            ),
            CustomTextField(
                onClick: (String value) {
                  if (_key.currentState!.validate()) {
                    email = value;
                  }
                },
                hint: 'Enter your email',
                icon: Icons.email_rounded),
            SizedBox(
              height: height * 0.02,
            ),
            CustomTextField(
                onClick: (String value) {
                  if (_key.currentState!.validate()) {
                    password = value;
                  }
                },
                hint: 'Enter your password',
                icon: Icons.lock),
            SizedBox(
              height: height * 0.05,
            ),
            MaterialButton(
              shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(8))),
              color: Colors.black,
              onPressed: () async {
                await MyAuth().sinIn(email!, password!);
              },
              child: const Text(
                'Register',
                style: TextStyle(fontSize: 20, color: Colors.white),
              ),
            ),
            SizedBox(
              height: height * 0.02,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  'have an account?',
                  style: TextStyle(fontSize: 20),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.of(context)
                        .pushReplacementNamed(LoginScreen.routName);
                  },
                  child: const Text(
                    'Login  ',
                    style: TextStyle(fontSize: 20),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    ),
  ),
  // ),
  );
 }
 }

my login screen code is :

import 'package:e_commerce/screens/register_screen.dart';
import 'package:e_commerce/servises/auth.dart';
import 'package:e_commerce/widgets/custom_input_field.dart';
import 'package:flutter/material.dart';
import 'package:e_commerce/constants.dart';

class LoginScreen extends StatefulWidget {
static String routName = 'login';
const LoginScreen({Key? key}) : super(key: key);

@override
State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
final GlobalKey<FormState> _key = GlobalKey<FormState>();
String? name;
String? password;
String? email;
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;

return Scaffold(
  backgroundColor: kMainColor,
  body: SingleChildScrollView(
    child: Container(
      padding: const EdgeInsets.only(top: 100),
      alignment: Alignment.center,
      child: Column(
        children: [
          Image.asset("assets/images/icons/cart.png"),
          const Text('Buy now',
              style: TextStyle(
                  fontFamily: 'Corinthia',
                  color: Colors.black,
                  fontSize: 40,
                  fontWeight: FontWeight.bold)),
          SizedBox(
            height: height * 0.05,
          ),
          CustomTextField(
              onClick: (String value) {
                if (_key.currentState!.validate()) {
                  email = value;
                }
              },
              hint: 'Enter your email',
              icon: Icons.email_rounded),
          SizedBox(
            height: height * 0.02,
          ),
          CustomTextField(
              onClick: (String value) {
                if (_key.currentState!.validate()) {
                  password = value;
                }
              },
              hint: 'Enter your password',
              icon: Icons.lock),
          SizedBox(
            height: height * 0.05,
          ),
          MaterialButton(
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(8))),
            color: Colors.black,
            onPressed: () {
              MyAuth().sinIn(email!, password!);
            },
            child: const Text(
              'Login',
              style: TextStyle(fontSize: 20, color: Colors.white),
            ),
          ),
          SizedBox(
            height: height * 0.02,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                'Don\'t have account?',
                style: TextStyle(fontSize: 20),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context)
                      .pushReplacementNamed(Register.routName);
                },
                child: const Text(
                  'Register  ',
                  style: TextStyle(fontSize: 20),
                ),
              )
            ],
            )
            ],
             ),
          ),
      ),
       // ),
     );
     }
      }

and I used Firebase authentication and create a class to use it I don't know if it may be the error come from it my authentication calss is :

import 'package:firebase_auth/firebase_auth.dart';

 class MyAuth {
 final _auth = FirebaseAuth.instance;
 Future sinIn(String email, String password) async {
  final authResult = await _auth.signInWithEmailAndPassword(
    email: email, password: password);
   return authResult;
 }

  Future register(String email, String password) async {
   final authResult = await _auth.createUserWithEmailAndPassword(
    email: email, password: password);
   return authResult;
    }
    }

the full error is :

════════ Exception caught by widgets library ═══════════════════════════════════
Closure call with mismatched arguments: function '_RegisterState.build.<anonymous closure>'
Receiver: Closure: (String) => Null
 Tried calling: _RegisterState.build.<anonymous closure>()
Found: _RegisterState.build.<anonymous closure>(String) => Null
The relevant error-causing widget was
CustomTextField
lib\screens\register_screen.dart:55
1 Answers

It looks like the mismatch is in the onClick method, which is declared here:

final Function? onClick; // it would help to further qualify Function here

You call it here, with no parameters:

    onSaved: onClick!(), // note no parameter

but when you pass it to the constructor, you are passing in a Function(String):

onClick: (String value) {

Make use of Dart's strong typing to say what type of function onClick is. Perhaps you meant it to be:

final Function()? onClick;

or

final Function(String)? onClick;

Also, in onSaved I think you probably intended:

onSaved: () => onClick!(); // provide a function here that calls onClick
Related