I’m trying to make a button that loses opacity when pressed, but I’m getting a message that saying I have dead code so the app won’t work.
main.dart
void main() {
runApp(const App());
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const LoginButton()
);
}
}
The error occurs here, saying the 0.5 in the conditional statement is dead code
login_button
class LoginButton extends StatelessWidget {
const LoginButton({super.key});
@override
Widget build(BuildContext context) {
bool pressed = false;
return Scaffold(
backgroundColor: Colors.black12,
body: Center(
child: GestureDetector(
onTap: (){
pressed = true;
} ,
child: AnimatedOpacity(
opacity: pressed ? 0.5 : 1,
duration: const Duration(milliseconds: 800),
child: Container(
width: 300,
height: 50,
decoration: ShapeDecoration(
color: const Color(0xFFE9ED1A),
shape: RoundedRectangleBorder(
side: const BorderSide(
width: 1.77,
color: Color(0xFFE9EC19),
),
borderRadius: BorderRadius.circular(6.18),
),
),
child: const Center(child: Text('Login')),
),
),
),
),
);
}
}
>Solution :
First: Since the widget is interactive, it has to be converted to a StatefulWidget.
Second: The bool pressed = false; has to be declared outside of th build method.
Third: The toggling of the pressed (in the GestureDetector – onTap) has to be inside a setState.
Here is the widget including the above fixes:
class LoginButton extends StatefulWidget {
const LoginButton({super.key});
@override
State<LoginButton> createState() => _LoginButtonState();
}
class _LoginButtonState extends State<LoginButton> {
bool pressed = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black12,
body: Center(
child: GestureDetector(
onTap: () {
setState(() {
pressed = !pressed;
});
},
child: AnimatedOpacity(
opacity: pressed ? 0.5 : 1,
duration: const Duration(milliseconds: 800),
child: Container(
width: 300,
height: 50,
decoration: ShapeDecoration(
color: const Color(0xFFE9ED1A),
shape: RoundedRectangleBorder(
side: const BorderSide(
width: 1.77,
color: Color(0xFFE9EC19),
),
borderRadius: BorderRadius.circular(6.18),
),
),
child: const Center(child: Text('Login')),
),
),
),
),
);
}
}
Tip:
Additionally, although your code works as expected, it seems the ElevatedButton can be a proper widget instead of having a Container wrapped with GestureDetector.