I am new to Flutter, I am working on a project, in the app I want to have a floating action button that dynamically changes its icon based on a certain condition.
For example, when the status is true, it should display a ✔️ icon, and when the status is false, it should display a ❌ icon.
I’ve tried the FloatingActionButton
widget, but it seems to only support a static icon.
How can I achieve this dynamic icon behaviour for the floating action button?
I would appreciate any guidance or code samples to help me implement this functionality!
This is my progress so far:
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool? isConditionTrue;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Floating Action Button Demo'),
),
body: Center(
child: Text(
'Your App Content',
style: TextStyle(fontSize: 24.0),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
isConditionTrue = !isConditionTrue;
});
},
child: Icon(
isConditionTrue ? Icons.check : Icons.add,
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: MyHomePage(),
));
}
3
Answers
Bro please initialize your Boolean it will work fine.
bool isConditionTrue = false;
like this
You’re on the right track but you could improve your code by making your
isConditionTrue
variable a boolean instead of aboolean?
. Using!isConditionTrue
on a variable that can be null is likely your problem. Think about this – ifisConditionTrue == null
, what would you expect the result to be?!null
is undefined.There are only two states needed for
isConditionTrue
–true
andfalse
. If you assignisConditionTrue
an initial value and make it a simple boolean, you’ll have better results.Here’s your code modified to fix this, but note that you could potentially set
isConditionTrue
totrue
to start if you’d rather.For trying dynamic icons, try this code.
Hope this will help.
Thanks 🙂