我有一个login_screen
父母,一个password_textfield
是孩子。
随着子级数据的更改,我想更新父级email
和password
的值。
父窗口小部件:
EmailTextField(email, focus, (value) {
setState(() {
email = value;
});
})
子窗口小部件:
import 'package:flutter/material.dart';
class EmailTextField extends StatefulWidget {
final FocusNode focus;
String email;
final Function onChange;
EmailTextField(this.email, this.focus, this.onChange);
@override
_EmailTextFieldState createState() => _EmailTextFieldState();
}
class _EmailTextFieldState extends State<EmailTextField> {
@override
Widget build(BuildContext context) {
return TextFormField(
onChanged: (value){
setState(() {
widget.email = value;
});
widget.onChange(value);
},
decoration: InputDecoration(labelText: 'Email'),
textInputAction: TextInputAction.next,
keyboardType: TextInputType.emailAddress,
onFieldSubmitted: (v) {
FocusScope.of(context).requestFocus(widget.focus);
},
);
}
}
答案 0 :(得分:0)
使用回调函数。
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String email='email';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
EmailTextField(
onChanged: (value) {
setState(
() {
email = value;
},
);
},
),
FlatButton(
onPressed: () {
//perform some action here
},
child: Text('Login'),
),
Text(email),
],
),
);
}
}
class EmailTextField extends StatelessWidget {
final Function onChanged;
EmailTextField({this.onChanged});
@override
Widget build(BuildContext context) {
return TextField(
onChanged: onChanged,
);
}
}