diff --git a/lib/pages/create_recipe_page.dart b/lib/pages/create_recipe_page.dart index 3b59276..c985a6a 100644 --- a/lib/pages/create_recipe_page.dart +++ b/lib/pages/create_recipe_page.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:rezepte/widgets/ingredients_bottomsheet.dart'; +import 'package:rezepte/widgets/will_pop_scope.dart'; import '../models/difficulty.dart'; import '../models/ingredient_list_entry.dart'; import '../services/providers/recipe_provider.dart'; @@ -25,8 +26,9 @@ class _CreateRecipeState extends State { @override Widget build(BuildContext context) { recipe = Provider.of(context); - return WillPopScope( - onWillPop: _onWillPop, + return CustomWillPopScope( + context, + ignore: recipe.isEmpty, child: Scaffold( appBar: AppBar( title: const Text('Create Recipe'), @@ -111,29 +113,4 @@ class _CreateRecipeState extends State { ), ); } - - Future _onWillPop() { - if (recipe.isEmpty) { - return Future( - () { - return true; - }, - ); - } - return showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('Leave the page?'), - content: const Text('Progress will be lost.'), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(false), - child: const Text('cancel')), - TextButton( - onPressed: () => Navigator.of(context).pop(true), - child: const Text('leave')), - ], - ), - ).then((value) => value ?? false); - } } diff --git a/lib/widgets/will_pop_scope.dart b/lib/widgets/will_pop_scope.dart new file mode 100644 index 0000000..0fc1c55 --- /dev/null +++ b/lib/widgets/will_pop_scope.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; + +class CustomWillPopScope extends StatelessWidget { + const CustomWillPopScope( + this.context, { + super.key, + required this.child, + this.ignore = false, + }); + + final Widget child; + final BuildContext context; + + /// If [ignore] is true, WillPopScope will automatically pop. + final bool ignore; + + Future _onWillPop() { + if (ignore) { + return Future( + () { + return true; + }, + ); + } + return showDialog( + context: context, + builder: _willPopDialogBuilder, + ).then((value) => value ?? false); + } + + @override + Widget build(BuildContext context) { + return WillPopScope(onWillPop: _onWillPop, child: child); + } +} + +Widget _willPopDialogBuilder(context) => AlertDialog( + title: const Text('Leave the page?'), + content: const Text('Progress will be lost.'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('cancel')), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('leave')), + ], + );