Flutter中已定义的onTap函数在GestureDetector引用时提示未定义
LoginPage中onTap函数未定义错误的解决办法
问题出在你访问onTap的方式上:你写的是Widget.onTap,这里的Widget是类的名称,而你实际需要调用的是当前LoginPage实例传递过来的onTap参数,在State类里应该用**小写的widget.onTap**来访问(State类自带的widget属性就是绑定的StatefulWidget实例)。
不管你有没有移除可空符号,只要访问方式错了,就会提示函数未定义。
修正后的关键代码片段
GestureDetector( onTap: widget.onTap, // 把大写的Widget改成小写的widget child: const Text( 'Create Account', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 15, color: Colors.black, ), ), ),
完整修正后代码
import 'package:finalproject/components/my_textfield.dart'; import 'package:flutter/material.dart'; // ignore: non_constant_identifier_names class LoginPage extends StatefulWidget { final void Function()? onTap; const LoginPage({super.key, required this.onTap}); @override State<LoginPage> createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { final emailController = TextEditingController(); final passwordController = TextEditingController(); // ignore: non_constant_identifier_names void SignIn() {} @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.grey[300], body: SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ //logo const Icon( Icons.message, size: 80, color: Colors.green, ), //welcome back message const Text( 'Welcome Back, You Have Been Missed', style: TextStyle( color: Colors.grey, fontSize: 20, fontStyle: FontStyle.italic, ), ), //create space const SizedBox( height: 20, ), //email textfield MyTextField( controller: emailController, hintText: 'Enter email', obsecuretext: false, ), //create space const SizedBox( height: 8, ), //password textfield MyTextField( controller: passwordController, hintText: 'Enter password', obsecuretext: true, ), const SizedBox( height: 8, ), //sign in button MyButton( onTap: () { SignIn(); }, text: 'Login', ), const SizedBox( height: 15, ), //not a member? register now Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'Not A Member?', style: TextStyle( // fontWeight: FontWeight.w600, fontSize: 13, color: Colors.black, ), ), const SizedBox( width: 10, ), GestureDetector( onTap: widget.onTap, child: const Text( 'Create Account', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 15, color: Colors.black, ), ), ), ], ) ], ), ), ), ); } }
内容的提问来源于stack exchange,提问作者katojkalemba
相关产品推荐
相关产品推荐

