Skip to content

Instantly share code, notes, and snippets.

@CaiJingLong
Last active July 29, 2021 14:34
Show Gist options
  • Save CaiJingLong/a7f40303338c1b843949b64487072cf2 to your computer and use it in GitHub Desktop.
Save CaiJingLong/a7f40303338c1b843949b64487072cf2 to your computer and use it in GitHub Desktop.
flutter 懒加载 切换保持状态
class HomeContainer extends StatefulWidget {
final List<Widget> children;
final int currentIndex;
const HomeContainer({
Key key,
this.children,
this.currentIndex,
}) : super(key: key);
@override
_HomeContainerState createState() => _HomeContainerState();
}
class _HomeContainerState extends State<HomeContainer> {
final initMap = <int, bool>{};
@override
void initState() {
super.initState();
initMap[0] = true;
}
@override
Widget build(BuildContext context) {
return IndexedStack(
children: createChildren(),
index: widget.currentIndex,
);
}
List<Widget> createChildren() {
final result = <Widget>[];
for (var i = 0; i < widget.children.length; ++i) {
final w = widget.children[i];
if (initMap[i] == true) {
result.add(w);
} else {
result.add(Container());
}
}
return result;
}
@override
void didUpdateWidget(HomeContainer oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.currentIndex != widget.currentIndex) {
initMap[widget.currentIndex] = true;
setState(() {});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment