1. 程式人生 > 實用技巧 >flutter 表單form 使用

flutter 表單form 使用

https://www.jianshu.com/p/9bec3d14df7f

大致用法如下

import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  
bool loading = false; String _username = ''; String _password = ''; // 驗證資料 登入 void _forSubmitted() async { var _form = _formKey.currentState; if (_form.validate()) { _form.save(); print(_username); print(_password); } } @override Widget build(BuildContext context) {
return Scaffold( appBar: AppBar( title: Text('登入'), ), body: GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { // 觸控收起鍵盤 FocusScope.of(context).requestFocus(FocusNode()); }, child: ListView( children:
<Widget>[ Form( key: _formKey, child: Container( margin: EdgeInsets.fromLTRB(10, 10, 10, 10), child: Column(children: <Widget>[ Container( margin: EdgeInsets.fromLTRB(0, 10, 0, 10), child: TextFormField( cursorColor: Theme.of(context).primaryColor, decoration: InputDecoration( hintText: '請輸入賬號', prefixIcon: Icon(Icons.person), ), validator: (val) { return val.length <= 0 ? "請輸入賬號" : null; }, onSaved: (val) { _username = val; }, ), ), Container( margin: EdgeInsets.fromLTRB(0, 10, 0, 10), child: TextFormField( cursorColor: Theme.of(context).primaryColor, obscureText: true, decoration: InputDecoration( hintText: '請輸入密碼', prefixIcon: Icon(Icons.lock), ), validator: (val) { if (val.length <= 0) { return '請輸入密碼'; } else { return val.length < 6 ? "密碼長度錯誤" : null; } }, onSaved: (val) { _password = val; }, ), ), Row( children: <Widget>[ Expanded( child: Container( height: 40, margin: EdgeInsets.fromLTRB(0, 10, 0, 10), child: RaisedButton( onPressed: this._forSubmitted, child: Text( '登 錄', style: TextStyle( fontSize: 20, ), ), textColor: Colors.white, color: Theme.of(context).primaryColor, ), ), ) ], ) ]), ), ), ], ), ), ); } }