refactored willpopscope

This commit is contained in:
SomnusVeritas
2023-11-01 15:03:27 +01:00
parent 0f1222040f
commit 83063f23d7
2 changed files with 52 additions and 27 deletions

View File

@@ -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<CreateRecipe> {
@override
Widget build(BuildContext context) {
recipe = Provider.of<RecipeProvider>(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<CreateRecipe> {
),
);
}
Future<bool> _onWillPop() {
if (recipe.isEmpty) {
return Future<bool>(
() {
return true;
},
);
}
return showDialog<bool>(
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);
}
}

View File

@@ -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<bool> _onWillPop() {
if (ignore) {
return Future<bool>(
() {
return true;
},
);
}
return showDialog<bool>(
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')),
],
);