Skip to content

Instantly share code, notes, and snippets.

@curioustechizen
Created May 22, 2020 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curioustechizen/b424985022624c3d8c94a0ea184d5699 to your computer and use it in GitHub Desktop.
Save curioustechizen/b424985022624c3d8c94a0ea184d5699 to your computer and use it in GitHub Desktop.
Flutter stateless widget blog: Step 2 - Toggle animation with an isSelected state
import 'package:flutter/material.dart';
const kSelectedColor = Colors.blueAccent;
const kUnselectedColor = Colors.transparent;
const kSelectedShadowOffset = Offset(0.0, 4.0);
final kSelectedBorderRadius = BorderRadius.circular(32.0);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: DecoratedBoxTransitionExample(),
),
),
);
}
}
class DecoratedBoxTransitionExample extends StatefulWidget {
@override
_DecoratedBoxTransitionExampleState createState() =>
_DecoratedBoxTransitionExampleState();
}
class _DecoratedBoxTransitionExampleState
extends State<DecoratedBoxTransitionExample>
with SingleTickerProviderStateMixin {
AnimationController _controller;
bool _isSelected = false;
final DecorationTween decorationTween = DecorationTween(
end: BoxDecoration(
color: kSelectedColor.withAlpha(32),
borderRadius: kSelectedBorderRadius,
boxShadow: <BoxShadow>[
BoxShadow(
color: kSelectedColor.withOpacity(0.2),
blurRadius: 8.0,
offset: kSelectedShadowOffset)
],
),
begin: BoxDecoration(
color: kUnselectedColor,
borderRadius: kSelectedBorderRadius,
// No shadow.
),
);
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this, duration: const Duration(milliseconds: 2000));
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: DecoratedBoxTransition(
position: DecorationPosition.background,
decoration: decorationTween.animate(
CurvedAnimation(parent: _controller, curve: Curves.easeInOut)),
child: Container(
width: 200,
height: 200,
child: Center(
child: Text(
"Content",
style: Theme.of(context)
.textTheme
.headline6
.copyWith(color: kSelectedColor),
)),
),
),
);
}
void _handleTap() {
_isSelected ? _controller.reverse() : _controller.forward();
setState(() {
_isSelected = !_isSelected;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment