I have a button (custom button based on the ElevatedButton) which I want to be disabled (or not) based on a bool variable (isCategorySet). isCategorySet comes from a Provider – so a Future.
I currently have it set up so the screen is built using a stateful class
class MyClass extends StatefulWidget {
@override
_MyClassState createState() => _MyClassState();
}
class _MyClassState extends State<MyClassProfiles> {
late Provider1 provider1;
late bool _iscategoryset;
At the beginning of _MyClassState I initialise:
@override
void initState() {
super.initState();
provider1 = Provider.of<provider1>(context, listen: false);
_checkCategory();
}
This is followed by my _checkCategory function:
//checks if any cateogries set
void _checkCategory() async {
await provider1.fetchSessions("category");
if (provider1.categoryList.isEmpty) {
//if no category set
_iscategoryset = false;
print('no category set $_iscategoryset');
} else {
// category is set
_iscategoryset = true;
print('category set $_iscategoryset');
}
}
The next part of the code builds the page and my button code looks like this:
CustomButtons.CustomButton(
text: "Sort by move",
onPress: () {
setState(() {
selectedSortOption = 'move';
});
},
),
OnPress is equivalent to OnPressed (CustomButton is derived from ElevatedButton).
I have tried writing a conditional as part of onPress, that calls the setState if _iscategoryset is true. But it does not seem to like that _iscategoryset is a future.
Do I have to take the button out and build it as a widget each time? I was hoping to avoid this!
Generally, Buttons can be disabled by setting onPressed
to null
.
The following example is a clear demonstration of the above words:
we have just a flag variable in which button is only clickable when this boolean flag is equal to true and the floating action button reverses the value of the flag variable
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool flag = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Test Diability of buttons')),
body:Container(
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
FilledButton(
child: Text('Pressable?'),
onPressed: flag ? (){} : null,
),
Text('Flag value is $flag'),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: reverseFlag,
tooltip: 'reverse',
child: const Icon(Icons.flag_circle_outlined),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void reverseFlag(){
setState((){
flag = !flag;
});
}
}