flutter - 如何提取此开关小部件
问题描述
我有一个带有 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;
});
},
),
),
],
),
),
解决方案
您可以像这样创建自己的无状态小部件:
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;
});
},
),
],
);
}
}
推荐阅读
- instagram - instagram 基本显示 API 获取请求不起作用?
- sql - 如何在 SQL 查询中创建一个附加列,其中包含列值等于当前行的列值的行数?
- tensorflow - 获取渐变的 nans
- python - 错误:找不到任何 FFTW 库 (Windows)
- c# - 使用反射构建 EF Core 查询比使用反射更快
- c - 如何以十进制形式存储前导零的整数值(无八进制数字)?
- python - Python difflib 给出了不好的结果
- python - 如何调整 ctypes 消息框的大小
- html - 您如何通过 CSS 正确调整 gif 的大小并将其放入 Youtube 的视频播放器中?
- gridview - 如何仅禁用在 gridview asp.net Web 表单中具有价值的列单元格?