Skip to content

Instantly share code, notes, and snippets.

@HansMuller
Last active January 8, 2024 18:33
Show Gist options
  • Save HansMuller/9e98e90eb3a8996c70126bf92481575b to your computer and use it in GitHub Desktop.
Save HansMuller/9e98e90eb3a8996c70126bf92481575b to your computer and use it in GitHub Desktop.
// Allow arbitrary foreground and background elements for ButtonStyle
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Home()));
}
class Home extends StatefulWidget {
const Home({ super.key });
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
late final Image inactiveImage;
late final Image hoveredImage;
late final Image pressedImage;
void initState() {
super.initState();
inactiveImage = Image.network(
'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Blue_Flower_Transparent_Background.png/640px-Blue_Flower_Transparent_Background.png',
key: UniqueKey(),
);
hoveredImage = Image.network(
'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Cactus_flower_extracted.png/480px-Cactus_flower_extracted.png',
key: UniqueKey(),
);
pressedImage = Image.network(
'https://upload.wikimedia.org/wikipedia/commons/f/f1/Tournesol.png',
key: UniqueKey(),
);
}
Widget imageForStates(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedImage;
}
if (states.contains(MaterialState.hovered)) {
return hoveredImage;
}
return inactiveImage;
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme;
return Scaffold(
body: Center(
child: TextButton(
onPressed: () {},
style: TextButton.styleFrom(
fixedSize: Size(400, 400),
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
child: imageForStates(states),
);
},
).copyWith(
overlayColor: MaterialStateProperty.all<Color>(Colors.transparent),
),
child: Text('Image Button'),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment