我的 Flutter 小部件定义:
class LoginFormWidget extends StatefulWidget {
const LoginFormWidget({
Key key,
@required this.loginFormKey,
@required this.isEnabled,
@required this.citiesListControl,
@required this.onPasswordLoginPressed,
@required this.onGuestLoginPressed,
@required this.onGoogleLoginPressed,
@required this.onFacebookLoginPressed,
@required this.onEmailSaved,
@required this.onPasswordSaved,
this.statusText,
}) : super(key: key);
//final GlobalKey<FormState> loginFormKey;
final Widget citiesListControl;
final bool isEnabled;
final String statusText;
final GlobalKey<FormState> loginFormKey;
final Function() onPasswordLoginPressed;
final Function() onGuestLoginPressed;
final Function() onGoogleLoginPressed;
final Function() onFacebookLoginPressed;
final Function(String) onEmailSaved;
final Function(String) onPasswordSaved;
@override
_LoginFormWidgetState createState() => _LoginFormWidgetState();
}
我定义了一些回调来处理登录按钮点击。对于登录电子邮件/密码,有一个登录按钮:
final loginButton = RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24.0),
),
onPressed: widget.onPasswordLoginPressed,
padding: EdgeInsets.all(12.0),
color: Colors.lightBlueAccent,
child: Text(Strings.btn_login, style: TextStyle(color: Colors.white), key: Key(Strings.btn_login)),
);
要使用我的小部件:
LoginFormWidget(
isEnabled: _isCitySelected,
onEmailSaved: (value) => _email = value,
onPasswordSaved: (value) => _password = value,
citiesListControl: citiesListControl,
statusText: _status,
loginFormKey: _loginFormKey,
onPasswordLoginPressed: _isCitySelected
? () {
if (_loginFormKey.currentState.validate()) {
_loginFormKey.currentState.save();
_loginEmailPassword();
}
}
: null,
因此,如果没有选择城市(_isCitySelected
为 false) - 按钮的 onPressed 应为空(按钮已禁用)。否则,应执行验证和表单保存。
如何在我的情况下执行表单验证?如果我将表单密钥传递给我的小部件(密钥在我的根小部件中定义)并按上述方式执行验证和保存,我将收到异常:
I/flutter (22322): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (22322): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter (22322): The method 'validate' was called on null.
I/flutter (22322): Receiver: null
I/flutter (22322): Tried calling: validate()
I/flutter (22322):
I/flutter (22322): When the exception was thrown, this was the stack:
I/flutter (22322): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
I/flutter (22322): #1 _LoginPageState._buildLoginForm.<anonymous closure> (package:lupe2/pages/login_page.dart:361:40)
I/flutter (22322): #2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:991:20)
I/flutter (22322): #3 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
I/flutter (22322): #4 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:607:11)
I/flutter (22322): #5 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
onEmailSaved: (value) => _email = value,
onPasswordSaved: (value) => _password = value,
是能够将表单值保存在我的小部件之外的回调函数。