Flutter / Dart:将参数传递给有状态的小部件?

问题描述

我需要调用将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})

我无法从另一个屏幕将title参数传递给它。 IE:

`EditPage(title:mytitle,oldtitle:myoldtitle);`

那么将参数传递给有状态的小部件的正确方法是什么?

解决方法

永远不要将变量直接传递给状态,因为它不保证在更新状态时将重新构建窗口小部件。您应该通过状态小部件接受参数,然后通过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),),);
  }
}
,

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...