import 'package:flutter/material.dart';
import 'package:get/get.dart';

abstract class GetxKeepAliveWidget<T extends GetxController> extends StatefulWidget {
  const GetxKeepAliveWidget({super.key});

  @override
  State<GetxKeepAliveWidget<T>> createState() => _GetxKeepAliveWidgetState<T>();

  Widget buildContent(BuildContext context, T controller);

  void initState() {}

  void dispose() {}
}

class _GetxKeepAliveWidgetState<T extends GetxController> extends State<GetxKeepAliveWidget<T>>
    with AutomaticKeepAliveClientMixin {
  T get controller => GetInstance().find<T>();

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    widget.initState();
    super.initState();
  }

  @override
  void dispose() {
    widget.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<T>(
      builder: (controller) => widget.buildContent(context, controller),
      assignId: true,
    );
  }
}
