Вызов закрытия с несоответствующими аргументами: функция ‘_RegisterState.build.’ Получатель: Закрытие: (Строка) => Null

# #android #firebase #flutter #android-studio #dart

#Android #огневая база #трепетать #android-студия #дротик

Вопрос:

Я не знаю, почему происходит эта ошибка, полная ошибка :

 Closure call with mismatched arguments: function '_RegisterState.build.lt;anonymous closuregt;' Receiver: Closure: (String) =gt; Null Tried calling: _RegisterState.build.lt;anonymous closuregt;() Found: _RegisterState.build.lt;anonymous closuregt;(String) =gt; Null  

Я думаю, что ошибка в многоразовом текстовом поле, которое я создал любым способом, его код здесь, мой код многоразового текстового поля :

 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' amp;amp; !value.contains('@')) {  return 'Enter valid email';  }  if (hint == 'Enter your Name' amp;amp; value.length lt; 3) {  return 'Enter valid Name';  }  if (hint == 'Enter your password' amp;amp; value.length lt; 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,  ),  ),  );  }  }  

Я использовал его в 2 экранах для входа и регистрации

мой код экрана регистрации: :

 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() =gt; _RegisterState(); }  class _RegisterState extends Statelt;Registergt; { String? name; String? email; String? password; final GlobalKeylt;FormStategt; _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 Statelt;LoginScreengt; createState() =gt; _LoginScreenState(); }  class _LoginScreenState extends Statelt;LoginScreengt; { final GlobalKeylt;FormStategt; _key = GlobalKeylt;FormStategt;(); 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),  ),  )  ],  )  ],  ),  ),  ),  // ),  );  }  }  

и я использовал аутентификацию Firebase и создал класс для ее использования, я не знаю, может ли это быть ошибкой, вызванной этим , моя проверка подлинности calss :

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

полная ошибка заключается в :

 ════════ Exception caught by widgets library ═══════════════════════════════════ Closure call with mismatched arguments: function '_RegisterState.build.lt;anonymous closuregt;' Receiver: Closure: (String) =gt; Null  Tried calling: _RegisterState.build.lt;anonymous closuregt;() Found: _RegisterState.build.lt;anonymous closuregt;(String) =gt; Null The relevant error-causing widget was CustomTextField libscreensregister_screen.dart:55  

Ответ №1:

Похоже, несоответствие кроется в onClick методе, который объявлен здесь:

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

Вы называете это здесь, без параметров:

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

но когда вы передаете его конструктору, вы передаете в Function(String) :

 onClick: (String value) {  

Используйте строгую типизацию Dart, чтобы сказать, что это за функция onClick . Возможно, вы хотели, чтобы это было:

 final Function()? onClick;  

или

 final Function(String)? onClick;  

Кроме того, onSaved я думаю, что вы, вероятно, намеревались:

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