Skip to content

Instantly share code, notes, and snippets.

@StanislawNagorski
Last active November 14, 2022 20:17
Show Gist options
  • Save StanislawNagorski/05ba2189eb3426b0771a8f11804ec787 to your computer and use it in GitHub Desktop.
Save StanislawNagorski/05ba2189eb3426b0771a8f11804ec787 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import '../presentation/styles/styles.dart';
const _defaultFit = BoxFit.fill;
const _defaultAlignment = Alignment.center;
const _defaultTextStyle = TextStyles.buttonBlack;
class TextWithChangingBackgroundButton extends HookWidget {
const TextWithChangingBackgroundButton({
required this.background,
required this.backgroundPressed,
required this.onTap,
required this.text,
this.enabled = true,
this.fit = _defaultFit,
this.alignment = _defaultAlignment,
this.textStyle = _defaultTextStyle,
this.disabledBackground,
this.height,
this.width,
this.margin,
Key? key,
}) : assert(
(!enabled && disabledBackground != null) || enabled,
'If you are disabling button plz provide disabledBackground',
),
super(key: key);
final String background;
final String backgroundPressed;
final Function onTap;
final String text;
final bool enabled;
final BoxFit fit;
final Alignment alignment;
final String? disabledBackground;
final double? height;
final double? width;
final EdgeInsets? margin;
final TextStyle? textStyle;
@override
Widget build(BuildContext context) {
final baseBackgroundAsset = AssetImage(enabled ? background : disabledBackground!);
final backgroundPressedAsset = AssetImage(backgroundPressed);
precacheImage(baseBackgroundAsset, context);
precacheImage(backgroundPressedAsset, context);
final image = useState(baseBackgroundAsset);
void _onTap() {
image.value = backgroundPressedAsset;
onTap();
image.value = baseBackgroundAsset;
}
void _onTapDown() => image.value = backgroundPressedAsset;
void _onTapCancel() => image.value = baseBackgroundAsset;
void _runFunctionIfButtonIsEnabled(Function action) {
if (enabled) action();
}
return GestureDetector(
onTap: () => _runFunctionIfButtonIsEnabled(_onTap),
onTapDown: (_) => _runFunctionIfButtonIsEnabled(_onTapDown),
onTapCancel: () => _runFunctionIfButtonIsEnabled(_onTapCancel),
child: Container(
height: height,
width: width,
margin: margin,
alignment: alignment,
decoration: BoxDecoration(
image: DecorationImage(
image: image.value,
fit: fit,
),
),
child: Text(
text,
style: textStyle,
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment