Ald*_*doB 3 flutter bottom-sheet
我在底部使用开关时遇到了一些问题.当我点击它时,它不会改变它的状态.只是第一次,状态正确改变.
这是我正在使用的简单代码:
bool _switchValue = false;
@override
Widget build(BuildContext context)
{
return new Scaffold(
body: Center(
child: RaisedButton(
child: const Text('SHOW BOTTOM SHEET'),
onPressed: () {
showModalBottomSheet<void>(context: context, builder: (BuildContext context) {
return Container(
child: CupertinoSwitch(
value: _switchValue,
onChanged: (bool value) {
setState(() {
_switchValue = value;
});
},
)
);
});
}
)
)
);
}
Run Code Online (Sandbox Code Playgroud)
谁能帮帮我吗?
Alb*_*bal 12
您需要将开关置于其自己的位置StatefulWidget
并使用回调将值返回到主类.底部工作表使用不同的上下文,因此setState
在上面的示例中调用不起作用.
class _MyHomePageState extends State<MyHomePage> {
bool _switchValue = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
child: const Text('SHOW BOTTOM SHEET'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return BottomSheetSwitch(
switchValue: _switchValue,
valueChanged: (value) {
_switchValue = value;
},
);
},
);
},
),
),
),
);
}
}
class BottomSheetSwitch extends StatefulWidget {
BottomSheetSwitch({@required this.switchValue, @required this.valueChanged});
final bool switchValue;
final ValueChanged valueChanged;
@override
_BottomSheetSwitch createState() => _BottomSheetSwitch();
}
class _BottomSheetSwitch extends State<BottomSheetSwitch> {
bool _switchValue;
@override
void initState() {
_switchValue = widget.switchValue;
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
child: CupertinoSwitch(
value: _switchValue,
onChanged: (bool value) {
setState(() {
_switchValue = value;
widget.valueChanged(value);
});
}),
);
}
}
Run Code Online (Sandbox Code Playgroud)
使用StatefulBuilder更改 BottomSheet 内开关的状态
showModalBottomSheet(
context: context, builder: (BuildContext context) {
return Container(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter stateSetter) {
return CupertinoSwitch(
value: _switchValue,
onChanged: (val) {
stateSetter(() => _switchValue = val);
},);
},
),
)
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1154 次 |
最近记录: |