import 'package:flutter/material.dart';

class LazyLoadIndexedStack extends StatefulWidget {
  final int index;
  final List<WidgetBuilder> children;

  const LazyLoadIndexedStack({
    super.key,
    required this.index,
    required this.children,
  });

  @override
  _LazyLoadIndexedStackState createState() => _LazyLoadIndexedStackState();
}

class _LazyLoadIndexedStackState extends State<LazyLoadIndexedStack> {
  final Map<int, Widget> _cachedWidgets = {};

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: widget.children.asMap().entries.map((entry) {
        int i = entry.key;
        WidgetBuilder builder = entry.value;

        // 如果页面已经加载过，则从缓存中获取
        if (!_cachedWidgets.containsKey(i) && i == widget.index) {
          _cachedWidgets[i] = builder(context); // 延迟加载
        }

        // 计算滑动方向
        double slideOffset = 0.0;
        if (i == widget.index) {
          slideOffset = 0.0; // 当前页面居中
        } else if (i < widget.index) {
          slideOffset = -MediaQuery.of(context).size.width; // 左侧页面
        } else {
          slideOffset = MediaQuery.of(context).size.width; // 右侧页面
        }

        return AnimatedPositioned(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          left: slideOffset,
          right: -slideOffset,
          top: 0,
          bottom: 0,
          child: AnimatedOpacity(
            duration: const Duration(milliseconds: 200),
            opacity: i == widget.index ? 1.0 : 0.0,
            child: _cachedWidgets[i] ?? const SizedBox.shrink(),
          ),
        );
      }).toList(),
    );
  }
}
