[英]How can I display or hide widget according to change in value using provider / State management( In flutter)?
This is how I want to display and remove a widget from different values.这就是我想从不同的值中显示和删除小部件的方式。
I note that the question title asks for using provider / State management, however I believe the base state management that Flutter uses is sufficient for this problem and using it would only overly complicate it.我注意到问题标题要求使用提供者/状态管理,但是我相信 Flutter 使用的基本状态管理足以解决这个问题,使用它只会过度复杂化。
You can use inline if statements to show widgets conditionally.您可以使用内联 if 语句有条件地显示小部件。 They require an else statement, so showing a SizedBox with a height of 0 can be used to show "nothing".
它们需要一个 else 语句,因此显示高度为 0 的 SizedBox 可用于显示“无”。
bool showWidget = false;
showWidget ? WidgetC() : SizedBox(height: 0)
Here is a working example.这是一个工作示例。 This one uses a bool value, but it could be anything, for example you could use
这个使用一个布尔值,但它可以是任何东西,例如你可以使用
_value > 3 ? WidgetC() : SizedBox(height: 0)
or或者
_value != "Test" ? WidgetC() : SizedBox(height: 0)
Here is example:这是示例:
class HideWidgetTest extends StatefulWidget {
const HideWidgetTest({Key? key}) : super(key: key);
@override
State<HideWidgetTest> createState() => _HideWidgetTestState();
}
class _HideWidgetTestState extends State<HideWidgetTest> {
bool _showWidget = true;
void _toggleShowWidget() {
setState(() {
_showWidget = !_showWidget;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
WidgetA(),
WidgetB(),
_showWidget ? WidgetC() : SizedBox(height: 0),
TextButton(
onPressed: () => _toggleShowWidget(),
child: Text('Hide Widget C')),
],
),
),
);
}
}
class WidgetA extends StatelessWidget {
const WidgetA({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text('Widget A');
}
}
class WidgetB extends StatelessWidget {
const WidgetB({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text('Widget B');
}
}
class WidgetC extends StatelessWidget {
const WidgetC({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text('Widget C');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.