我有一个父小部件,它调用我制作的自定义 Switch 小部件。我需要父小部件中开关的值(无论是打开还是关闭)。我可以在我的开关小部件中创建一个返回该值的控制器吗?
目前,我正在从父窗口小部件传递该函数,该函数根据开关窗口小部件中的开关值更改父窗口小部件中的布尔值。
父小部件:
bool isSwitchOn = false;
Switch(onSwitchToggle: (bool val) {
isSwitchOn = val;
})
Run Code Online (Sandbox Code Playgroud)
自定义开关小部件:
class Switch extends StatefulWidget {
Widget build(BuildContext context) {
return CupertinoSwitch(
value: widget.value,
onChanged: (bool value) {
setState(() {
widget.value = value;
});
widget.onSwitchToggle(value);
},
),
}
Run Code Online (Sandbox Code Playgroud)
每当我需要开关时,代码中的任何地方都会使用开关小部件,有时我不需要知道开关的状态,我只需要在切换开关时执行一个函数,但我编写代码的方式,每当我调用开关时,我都需要在各处传递 bool 。寻找更好的方法来做到这一点。例如: Bool val 是不必要的,因为我不需要它。
Switch(onSwitchToggle: (bool val) {
print('abc')
})
Run Code Online (Sandbox Code Playgroud) 我需要构建一个轮播滑块,在图像下方包含图像和文本,并且图像约束需要为 250 x 250。我将图像和文本放在一列内,但它们被切断,说底部有溢出。如果我给 CarouselSlider 小部件一个高度,它会起作用,但我不应该这样做,因为文本会变化并且给出的高度不会一致。尝试了其他几种方法,例如 Wrap、Expanded,但似乎都不起作用
这就是我正在做的::
final List<String> imgList = [
'https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80',
'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',
];
Widget build(BuildContext context) {
return Container(
child: CarouselSlider(
//height: 350, //giving this a height fixes it but I shouldn't be doing it
items: imgList.map((i) {
return
Column(
children: [
Container(
margin: EdgeInsets.symmetric(horizontal: 5.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Image.network(i, height: 250, width: 250)),
),
Text(i)
],
);
}).toList(),
viewportFraction: 1.0,
)
Run Code Online (Sandbox Code Playgroud)