flutter - Toggle between pages function returns null (flutter)
问题描述
I tried maybe 4 different ways to write the code for toggling between the sign in page and the register page using a toggle function but it always gave me an error but this type doesn't give me an error in the code it prints an error in the run console that says "The following _CastError was thrown while handling a gesture: Null check operator used on a null value"
This is my authentication file 'authenticate.dart':
class _AuthenticateState extends State<Authenticate> {
bool showSignIn = false;
void Function()? toggleView() {
setState(() => showSignIn = !showSignIn);
}
@override
Widget build(BuildContext context) {
if(showSignIn) {
return SignIn(toggleView: toggleView());
} else {
return Register(toggleView: toggleView());
}
}
}
This is my 'register.dart' file:
class Register extends StatefulWidget {
final void Function()? toggleView;
Register({ required this.toggleView});
@override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
final AuthService _auth = AuthService();
//text field state
String email = '';
String password = '';
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.brown[100],
appBar: AppBar(
backgroundColor: Colors.brown[400],
elevation: 0,
title: Text('Sign up to the breakfast club'),
actions: [
TextButton.icon(
icon: Icon(
Icons.person,
),
label: Text('Sign In'),
onPressed: () {
print('Sign in clicked');
widget.toggleView!();
},
style: TextButton.styleFrom(
primary: Colors.white,
),
),
And my 'sign_in.dart' is exactly the same as 'register.dart' except for this part:
onPressed: () {
print('Register clicked');
widget.toggleView!();
},
解决方案
I think the problem here is you sending through a function toggleView() which is not the same as sending through the function itself with all the scope of its parameters in tact. You want to create a callback.
You should place all of the function definition in the parameter without naming it eg:
Register(toggleView: () {setState(() => showSignIn = !showSignIn);});
This way the scope of the showSignIn parameter is clear and refers to the variable of that name in the Authentication.dart file.
推荐阅读
- jpa - 卡在将值从 selectcheckboxmenu 传递到 managedbean
- c# - 在循环内创建列表时,由于其保护级别而无法访问
- python-3.x - 通过 id 和 date 使用 pivot/groupby 重塑数据框
- json - 对 Flask Rest API 的 Ajax 调用未获取 JSON
- html - 为什么 position:sticky 不能与 flexbox 一起使用?
- oauth-2.0 - 使用 Google OAuth 2.0 进行用户身份验证
- node.js - MEAN Stack - SPA webapp 上的 *refresh*
- wso2 - 如何更改 wso2 esb 中的标题标签
- amazon-web-services - 挂载 AWS EFS 后无法访问 Drupal 站点
- python - 从 Excel 中的 CSV 到 Pandas 的日期格式不正确