Meg*_*ggy 5 widget stateful parameter-passing dart flutter
我需要调用将我的title和oldtitle参数传递给我的EditPageStateful 小部件。但如果我这样做;
class EditPage extends StatefulWidget {
String title;
String oldtitle;
EditPage({this.title, this.oldtitle})
Run Code Online (Sandbox Code Playgroud)
这些字符串不可用于构建,除非我将其称为 widget.title和widget.oldtitle。
但我正在使用一个textfield表单,如果我使用这些小部件,它似乎无法正常工作。
这是表单代码:
Container(
child: TextField(
decoration: new InputDecoration(
hintText: widget.oldtitle,
contentPadding: new EdgeInsets.all(1.0),
border: InputBorder.none,
filled: true,
fillColor: Colors.grey[300],
),
keyboardType: TextInputType.text,
autocorrect: false,
onChanged: (titleText) {
setState(() {
widget.title= titleText;
});
},
),
),
Run Code Online (Sandbox Code Playgroud)
但如果我这样做;
class _EditPageState extends State<EditPage> {
String title;
String oldtitle;
EditPage({this.title, this.oldtitle})
Run Code Online (Sandbox Code Playgroud)
我无法从另一个屏幕将标题参数传递给它。IE:
`EditPage(title:mytitle, oldtitle:myoldtitle);`
Run Code Online (Sandbox Code Playgroud)
那么将参数传递给 Stateful widget 的正确方法是什么?
小智 11
您永远不应该将变量直接传递给状态,因为它不能保证状态更新时小部件将被重建。您应该通过有状态小部件接受参数,并通过 状态本身访问它们widget.variable。
例子:
class TestWidget extends StatefulWidget {
final String variable;
TestWidget({Key key, @required this.variable}) : super(key: key);
@override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
@override
Widget build(BuildContext context) {
return Container(
child: Center(
// Accessing the variables passed into the StatefulWidget.
child: Text(widget.variable),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
看起来解决方案是将标题与旧标题分开;
class EditPage extends StatefulWidget {
String oldtitle;
EditPage({this.oldtitle})
Run Code Online (Sandbox Code Playgroud)
进而;
class _EditPageState extends State<EditPage> {
String title;
Run Code Online (Sandbox Code Playgroud)
现在是表格;
Container(
child: TextField(
decoration: new InputDecoration(
hintText: widget.oldtitle,
contentPadding: new EdgeInsets.all(1.0),
border: InputBorder.none,
filled: true,
fillColor: Colors.grey[300],
),
keyboardType: TextInputType.text,
autocorrect: false,
onChanged: (titleText) {
setState(() {
title= titleText;
});
},
),
),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12753 次 |
| 最近记录: |