从自定义输入窗口小部件获取值

时间:2018-12-13 11:40:35

标签: dart flutter

我通过将Textfield包装在一些小部件中来制作了一个自定义输入小部件,依此类推。现在,我无法直接从自定义窗口小部件访问onChanged属性。我尝试在自定义窗口小部件中创建属性,但无法正确实现。我用谷歌搜索在小部件之间传递变量,这似乎很难。有什么简单的解决方案吗?

class Input extends StatelessWidget {
  final String text;
  final TextInputType type;
  final int maxLength;
  final bool password;
  final String label;
  final IconData icon;
  final double padding;
  final Function onChanged;
  final ColorSwatch color;

  Input(
      {this.type = TextInputType.text,
      @required this.text,
      this.maxLength,
      this.icon,
      this.padding = 0.0,
      this.password = false,
      @required this.onChanged,
      this.label,
      this.color});

  final String value = '';

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(padding),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(3.0),
            child: Text(
              text + ":",
              style: TextStyle(fontSize: 15.0, color: color),
            ),
          ),
          Container(
            padding: EdgeInsets.all(3.0),
            width: 300.0,
            child: TextField(
              obscureText: password,
              decoration: InputDecoration(
                labelText: label,
                icon: Icon(icon),
              ),
              maxLength: maxLength,
              keyboardType: type,
              textInputAction: TextInputAction.next,
              onChanged: onChanged,
            ),
          ),
        ],
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

即使您只是将它们提供给基础TextField,也需要在自定义窗口小部件中提供onChanged和其他事件。换句话说,需要将onChanged函数向下传递到自定义小部件。

例如:

MyAwesomeTextField extends StatelessWidget {
  /// Callback for being notified of changes to the text field
  /// This should have a proper type, I'm just using Function for simplicity
  final Function onChanged; 

  // Make the onChanged property settable through the constructor
  MyAwesomeTextField({this.onChanged});

  Widget build(BuildContext context) {
    // Construct your widget tree, and pass your onChanged function through
    return TextField(onChanged: this.onChanged);
  }
}

然后,当您使用它时,您的自定义窗口小部件将具有onChanged事件:

...
MyCustomWidget(onChanged: (value) => print(value) )
...
相关问题