TextFormField数据处理

重点:TextFormField这个Widget是由TextField封装而来,继承了TextField的特性:
数据传递依靠:
GlobalKey<FormState>(),
RegisterKey.currentState.save();
加上Form里面有key选项,这三项复合起来,可以达到数据传递的目的。具体请看如下示例:


import 'package:flutter/material.dart';


void main()=>runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: HomePage(),
),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
final RegisterKey=GlobalKey<FormState>();
String username, password;

void submitForm(){
RegisterKey.currentState.save();
debugPrint('username:$username');
debugPrint('password:$password');
}

@override
Widget build(BuildContext context) {
return Form(
key:RegisterKey,
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10.0),
child: TextFormField(
decoration: InputDecoration(
labelText: 'Please input username',
contentPadding: EdgeInsets.all(20),
),
onSaved: (value){
username=value;
},
),
),
Container(
padding: EdgeInsets.all(10.0),
child: TextFormField(
obscureText: true,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(20),
labelText: 'Please input password',
),
onSaved: (value){password=value;},
),
),
SizedBox(height: 10,),
Container(
padding: EdgeInsets.all(20.0),
width: double.infinity,
child: RaisedButton(
onPressed:submitForm,
color: Colors.lightGreen,
child: Text('点我哦'),
),
),
],
),
);
}
}

posted @ 2019-04-19 18:56  braveheart007  阅读(1184)  评论(0编辑  收藏  举报