首页 > 解决方案 > 如何提取此开关小部件

问题描述

我有一个带有 ListView 的 StatefulWidget,ListView 旁边有一堆带有文本的开关。现在我想将它提取到自定义开关小部件中,因为我不止一次拥有它。我不知道该怎么做,我还需要在我的父小部件中知道每个开关的状态。

Padding(
  padding: const EdgeInsets.only(left: 16.0),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      Text("Use custom dhcp server"),
      Padding(
        padding: const EdgeInsets.only(right: 8.0),
        child: Switch(
          value: _dhcp,
          activeColor: Colors.blue,
          onChanged: (bool value) {
            setState(() {
              _dhcp = value;
            });
          },
        ),
      ),
    ],
  ),
),

标签: flutterdartwidget

解决方案


您可以像这样创建自己的无状态小部件:

class CustomSwitch extends StatelessWidget {
  const CustomSwitch({
    Key key,
    @required this.value,
    @required this.onChanged,
  }) : super(key: key);

  final bool value;
  final void Function(bool) onChanged;

  @override
  Widget build(BuildContext context) {
    return Switch(
      value: value,
      activeColor: Colors.blue,
      onChanged: onChanged,
    );
  }
}

您可以在任何地方使用它,如下所示:

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  bool switchValue = false;

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        CustomSwitch(
          value: switchValue,
          onChanged: (newValue) {
            setState(() {
              switchValue = newValue;
            });
          },
        ),
      ],
    );
  }
}

推荐阅读