Reputation: 21
I'm building a restaurant menu app and one of the features of the menu is to allow the users to pick their allergies so the app will turn the menu items containing those allergenics unclickable.
bool allergies = false;
Visibility(
visible: allergies,
child: Plate_Widget())
Some plates, turns out can have multiple allergenics so I need a way to set multiple booleans per each widget. If I set multiple bools or a list of bools flutter says:
Too many positional arguments: 0 expected, but 1 found.
Upvotes: 1
Views: 454
Reputation: 20118
Good question!
To show a Visibility
widget based on multiple conditions, you can create your own widget that accepts a list of bool
s:
class CustomVisibility extends StatelessWidget {
final List<bool> conditions;
final Widget child;
const CustomVisibility(
{required this.conditions, required this.child, Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return Visibility(
// returns true if all `conditions` are true, returns false otherwise
visible: conditions.every((element) => element),
child: child,
);
}
}
And then you can call it as follows:
class MyWidget extends StatelessWidget {
final isVisible = true;
final condition2 = true;
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return CustomVisibility(
conditions: [isVisible, condition2], child: const Text('Hello'));
}
}
Here's a complete runnable snippet:
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
final isVisible = true;
final condition2 = true;
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return CustomVisibility(
conditions: [isVisible, condition2], child: const Text('Hello'));
}
}
class CustomVisibility extends StatelessWidget {
final List<bool> conditions;
final Widget child;
const CustomVisibility(
{required this.conditions, required this.child, Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return Visibility(
// if all conditions are true, then show the child
visible: conditions.every((element) => element),
child: child,
);
}
}
Upvotes: 2