Flutter 入门与实战(九),android 软件开发前景
bool obscureText = false,height = 50.0,}) {return Container(height: height,margin: EdgeInsets.all(10.0),child: Column(children: [TextField(keyboardType: keyboardType,focusNode: focusNode,obscureText: obscureText,controller: controller,decoration: decoration,onChanged: onChanged,),Divider(height: 1.0,color: Colors.grey[400],),],),);}
完整代码
class _LoginPageState extends State<LoginPage> {//TextEditingController 可以使用 text 属性指定初始值 TextEditingController _usernameController = TextEditingController();TextEditingController _passwordController = TextEditingController();String _username = '', _password = '';
@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text('登录'),brightness: Brightness.dark,),body: Center(child: Column(crossAxisAlignment: CrossAxisAlignment.center,mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[_getRoundImage('images/logo.png', 100.0),SizedBox(height: 60,),_getUsernameInput(),_getPasswordInput(),SizedBox(height: 10,),_getLoginButton(),],),),);}
Widget _getUsernameInput() {return _getInputTextField(TextInputType.number,controller: _usernameController,decoration: InputDecoration(hintText: "输入手机号",icon: Icon(Icons.mobile_friendly_rounded,size: 20.0,),border: InputBorder.none,//使用 GestureDetector 实现手势识别 suffixIcon: GestureDetector(child: Offstage(child: Icon(Icons.clear),offstage: _username == '',),//点击清除文本框内容 onTap: () {this.setState(() {_username = '';_usernameController.clear();});},),),//使用 onChanged 完成双向绑定 onChanged: (value) {this.setState(() {_username = value;});},);}
Widget _getPasswordInput() {return _getInputTextField(TextInputType.text,obscureText: true,controller: _passwordController,decoration: InputDecoration(hintText: "输入密码",icon: Icon(Icons.lock_open,size: 20.0,),suffixIcon: GestureDetector(child: Offstage(child: Icon(Icons.clear),offstage: _password == '',),onTap: () {this.setState(() {_password = '';_passwordController.clear();});},),border: InputBorder.none,),onChanged: (value) {t
his.setState(() {_password = value;});},);}
//省略了上述列举的代码
}
页面跳转
在上层面的登录按钮上,我们增加了一个点击事件,点击后再跳到登录页,按钮的响应代码如下所示。这是页面跳转的最简单的方式,使用 Navigator 导航器的 push 方法实现页面跳转,后续会介绍如何通过路由实现页面跳转,那种方式更为优雅。//...onPressed: () {Navigator.of(context).push(MaterialPageRoute(builder: (context) => LoginPage()),);},//...
总结
从代码上看,功能虽然实现了,但是构建用户名和密码的代码十分相似,有没有办法进一步提高代码复用率,构建一个更为通用的表单组件呢?下篇我们将介绍如何来封装。
评论