I want to implement a feature where the user can exit the app by pressing the back button twice,
But when i first press the button ‘currentBackPressTime’ and ‘now’ are almost ths same time,ress the button for the second time and after, it works well!. ,what’s wrong with it?
Here is my flutter code:
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
static DateTime currentBackPressTime = DateTime.now();
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
builder: EasyLoading.init(),
home: WillPopScope(
onWillPop: () async {
DateTime now = DateTime.now();
print(currentBackPressTime);
print(now);
if (now.difference(currentBackPressTime) >
const Duration(milliseconds: 1200)) {
currentBackPressTime = now;
EasyLoading.showToast('Press agin to exit!',
duration: const Duration(milliseconds: 1200));
return false;
}
return true;
},
child: const MyLayout()),
);
}
}
I waited for quite some time until the app finished rendering before pressing the button. In theory, there should have been a long time gap between the two events.
2
Answers
Your approach is problematic because
static
variables are initialized lazily, socurrentBackPressTime
is initialized to the current time the first time it’s accessed, not when your application starts.You instead either should:
Keep track of the previous time that the back button was pressed, as Aks suggested.
Initialize
currentBackPressTime
to an arbitrary time known to be well into the past (e.g.DateTime(0)
).