I am trying to create a button that fades in opacity when pressed.
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()
);
}
}
login_button.dart:
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: Opacity(
opacity: pressed ? 0.5 : 1,
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')),
),
),
),
),
);
}
}
The problem is the app is saying I have dead code in the login_button.dart file. I know I can also use the ElevatedButton widget but I have to use a button that looks like this & I can’t get the ElevatedButton to look like this at all. I don’t understand why the code is dead & why it doesn’t work. What am I doing wrong?
2
Answers
Instead of Opacity use AnimatedOpacity so that the fade in gives a clear and animated look.
You’re using StatelessWidget, so when you change
pressed
value, it won’t rebuild the UI -> nothing happenedQuick solution: change your class to StatefulWidget, and use
setState
to changepressed
value. You should useonTapDown
&onTapUp
instead ofonTap
which causes the button still fade out when you release your finger (which should not right?)