您如何从此窗口小部件树创建独立窗口小部件?

时间:2019-06-13 21:53:23

标签: flutter

我有一个表示简单数据选择器表单字段的小部件树:

GestureDetector(
  onTap: () => _showDataPicker(context),
  child: AbsorbPointer(
    absorbing: true,
    child: TextFormField(
        controller: _controller,
        decoration: new InputDecoration(
            border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20)),
            suffixIcon: Icon(Icons.lock_open),
            icon: Icon(Icons.lock),
            hintText: "Password"),
        validator: (String value) {
          return null;
          if (value.isEmpty)
            return "Password can't be empty";
          else if (value.length < 8)
            return "Password must contain at least 8 chars";

          return null;
        }),
  ),
),

它只是一个文本格式字段,被AbsorbPointer包围以禁用其上的输入。通过该代码,我想创建一个自定义窗口小部件,可以将其插入窗口小部件树的任何其他部分。像这样:

CustomFormDataPicker(
    validator: (value) {},
)

您将如何做?您是否将从FormField继承(因为我希望始终在表单中使用它)。您是否将从顶级componenet GestureDetector继承并保留对TextFormField的引用(不知道这将如何与父Form一起使用)?

我在这里有点迷。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

检查此代码。如果您需要进一步的解释,请不要犹豫,让我知道。

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Material(
      child: CustomFormDataPicker(
        validator: (String value) {
          // return null;
          if (value.isEmpty)
            return "Password can't be empty";
          else if (value.length < 8)
            return "Password must contain at least 8 chars";

          return null;
        },
      ),
    );
  }

}

typedef ShowDataPickerCallback = void Function(BuildContext context);

class CustomFormDataPicker extends StatelessWidget {
  final String Function(String message) validator;
  final ShowDataPickerCallback showDataPicker;

  CustomFormDataPicker({this.validator, this.showDataPicker});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => showDataPicker != null ? showDataPicker(context) : null,
      child: AbsorbPointer(
        absorbing: true,
        child: TextFormField(
            controller: _controller,
            decoration: new InputDecoration(
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20)),
                suffixIcon: Icon(Icons.lock_open),
                icon: Icon(Icons.lock),
                hintText: "Password"),
            validator: validator),
      ),
    );
  }
}

答案 1 :(得分:0)

如果您使用的是VSCode,则可以使用其快捷方式,称为提取小部件。