Reputation: 2179
There's a AnimatedSwitcher
in my view which animates the page transition. I want to disable all click events while transition animation is running. Here's what I've tried:
class _MainPageState extends State<MainPage> {
int pageIndex = 1;
bool disableClicks = false;
@override
Widget build(BuildContext context) {
return AbsorbPointer(
absorbing: disableClicks,
child: Scaffold(
body: AnimatedSwitcher(
duration: 500.milliseconds,
child: pageIndex == 0
? Container(color: Colors.red, key: UniqueKey())
: pageIndex == 1
? Container(color: Colors.blue, key: UniqueKey())
: Container(color: Colors.green, key: UniqueKey()),
transitionBuilder: (child, animation) {
animation.addStatusListener((status) {
switch (status) {
case AnimationStatus.forward:
case AnimationStatus.reverse:
if (mounted && !disableClicks)
setState(() {
disableClicks = true;
});
break;
case AnimationStatus.dismissed:
case AnimationStatus.completed:
if (mounted && disableClicks)
setState(() {
disableClicks = false;
});
break;
}
});
return FadeTransition(child: child, opacity: animation);
},
),
),
);
}
}
But apparently I'm using setState
while page is building and Flutter is throwing Exception:
setState() or markNeedsBuild() called during build.
What is the proper way to achieve this?
Upvotes: 0
Views: 577
Reputation: 46
I think you should try ValueNotifier
and ValueListenableBuilder()
.
class TwoCents extends StatelessWidget {
final ValueListenable<bool> disableClicks;
@override
Widget build(BuildContext context) {
return ValueListenableListener(
valueListenable: disableClicks,
onChange: (value) {
// do something
},
child: ThreeCents(),
);
}
}
Upvotes: 1