6.2 获取输入框的值(方法1)
1.源代码
import 'package:flutter/material.dart';
void main () => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String saveText = "";
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
autofocus: true,
decoration: InputDecoration(
prefixIcon:Icon(Icons.perm_identity),
labelText: "用户名",
hintText: "请输入用户名",
hintStyle: TextStyle(
color: Colors.grey,
),
),
onChanged: (value){
saveText = value;
},
),
TextField(
obscureText: true,
decoration: InputDecoration(
prefixIcon:Icon(Icons.lock),
labelText: "密码",
hintText: "请输入密码",
hintStyle: TextStyle(
color: Colors.grey,
),
),
),
Builder(
builder: (context)=>RaisedButton(
onPressed: (){
Scaffold.of(context).showSnackBar(new SnackBar(content:new Text(saveText)));
},
child: Text("点击显示输入框的值"),
)
)
],
),
)
)
);
}
}
2.解释源代码
import 'package:flutter/material.dart';
void main () => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String saveText = "";
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
autofocus: true,
decoration: InputDecoration(
prefixIcon:Icon(Icons.perm_identity),
labelText: "用户名",
hintText: "请输入用户名",
hintStyle: TextStyle(
color: Colors.grey,
),
),
onChanged: (value){
saveText = value;
},
),
TextField(
obscureText: true,
decoration: InputDecoration(
prefixIcon:Icon(Icons.lock),
labelText: "密码",
hintText: "请输入密码",
hintStyle: TextStyle(
color: Colors.grey,
),
),
),
Builder(
builder: (context)=>RaisedButton(
onPressed: (){
Scaffold.of(context).showSnackBar(new SnackBar(content:new Text(saveText)));
},
child: Text("点击显示输入框的值"),
)
)
],
),
)
)
);
}
}
3.效果图