Flutter/Dart: 如何向有状态的小部件传递参数?

5

我需要将titleoldtitle参数传递给我的EditPage可变状态组件。但如果我这样做;

 class EditPage extends StatefulWidget {
   String title;  
   String oldtitle;
   EditPage({this.title, this.oldtitle})

除非我将它们作为widget.titlewidget.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;
                    });
                  },
                ),
              ),

但是如果我这样做的话;

class _EditPageState extends State<EditPage> {
   String title;  
   String oldtitle;  
   EditPage({this.title, this.oldtitle})

我无法从另一个屏幕将标题参数传递给它。例如:
`EditPage(title:mytitle, oldtitle:myoldtitle);`

那么,向Stateful小部件传递参数的正确方式是什么?


thistitle 没有声明。你可能想说的是 this.title。静态分析应该显示这个错误。 - Christopher Moore
谢谢,这个错误是我在编辑Stackoverflow时犯的。完整的代码相当庞大。我已经将其编辑为this.title。 - Meggy
widget. 是从状态访问小部件参数的正确方法。请澄清此方法的实际问题。 - Christopher Moore
2个回答

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),
      ),
    );
  }
}

如果是这样,我猜测我的问题在于表单而不是参数传递。我尝试了你的代码,但我的表单仍然无法正常工作。我将编辑以包括表单的代码; - Meggy
1
这似乎不再起作用了。错误显示变量不能为空。 - nikoss

1

看起来解决方案是将标题与旧标题分开;

  class EditPage extends StatefulWidget {
     String oldtitle;
     EditPage({this.oldtitle})

然后;

 class _EditPageState extends State<EditPage> {
  String title;     

现在该谈论表格了;
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;
                });
              },
            ),
          ),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接