import 'package:flutter/material.dart';

// ignore: must_be_immutable
class WillExitApp extends StatelessWidget {
  final Widget child;
  WillExitApp({
    Key? key,
    required this.child,
  }) : super(key: key);

  DateTime? _currentBackPressTime;

  Future<bool> onWillPop(BuildContext context) {
    DateTime now = DateTime.now();
    print(_currentBackPressTime);
    if (_currentBackPressTime == null ||
        now.difference(_currentBackPressTime!) > Duration(seconds: 2)) {
      const snackBar = SnackBar(
        content: Text("กด Back อีกครั้งเพื่อออก"),
      );
      _currentBackPressTime = now;
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
      return Future.value(false);
    }
    return Future.value(true);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () => onWillPop(context),
      child: this.child,
    );
  }
}
