Skip to content

Instantly share code, notes, and snippets.

@reedom
Created March 4, 2021 10:50
Show Gist options
  • Save reedom/fe623229546a752ed2e16dc4a828ba89 to your computer and use it in GitHub Desktop.
Save reedom/fe623229546a752ed2e16dc4a828ba89 to your computer and use it in GitHub Desktop.
An improved IndexStack, suppress flickering on switching to another widget.
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
class OptimizedIndexedStack extends HookWidget {
const OptimizedIndexedStack({
Key key,
@required this.pages,
this.index = 0,
}) : super(key: key);
final List<Widget> pages;
final int index;
@override
Widget build(BuildContext context) {
// Suppress flickering.
// When switching to another:
// 1. Show both of widgets.
// 2. At the next frame, hide the old one.
final prevIndex = useState(index);
if (prevIndex.value != index) {
Future<void>.delayed(Duration.zero).then((_) => prevIndex.value = index);
}
return Stack(
children: List.generate(pages.length, (i) {
final page = pages[i];
return Visibility(
visible: i == index || i == prevIndex.value,
maintainState: true,
child: page,
);
}).toList(),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment