Reputation: 775
I am creating an app where I have complete manual control over every back button press.
I basically have widgets/views changing in my app instead of the Navigator pushing and popping new screens.
I created a function where I am able to display views 1,2 and 3. and go back using the back button on android. however in case of iOS the back gesture does not work and I am unable to change views.
any workaround? Help would be appreciated
Future<bool> goBackward(){
if(_isButtonPressed) {
if(currentView == 0)
{
return Future<bool>.value(true);
}
else if(currentView == 1)
{
currentView = 0;
notifyListeners();
return Future<bool>.value(false);
}
else
{
currentView = 2;
notifyListeners();
return Future<bool>.value(false);
}
}
}
above is minimal version of code. when I return true that means I'm ready to Pop screen on back press
Upvotes: 9
Views: 7411
Reputation: 21
Put this as your top-level widget, possibly inside the build function:
bool canNavigateBack = true;//This should come from a Stream/bloc/etc.
return WillPopScope(
onWillPop: () {
if (Platform.isAndroid) {
if (canNavigateBack) {
//Navigate back actions
} else {
//Show exit dialog, etc.
}
}
return Future.value(false);
},
child: Platform.isIOS
? GestureDetector(
onHorizontalDragEnd: (details) {
if (details.velocity.pixelsPerSecond.dx > 50) {
if (canNavigateBack) {
//Navigate back actions
} else {
//Show exit dialog, etc.
}
}
},
child: _anotherWidget())
: _anotherWidget(),
);
Note: Only works if you develop your app for Android / iOS.
Upvotes: 1
Reputation: 775
After searching on the web and trying numerous packages like cupertino_will_pop_scope and back_button_interceptor I found that none of them worked for my use case.
cupertino_will_pop_scope was a miss and hit thing so sometimes it worked and sometimes it didnt.
here is a solution for anyone who hasn't found an answer to this yet.
as I mentioned before the WillPopScope works perfectly on android so no need to change functionality over there.
for IOS however I used Gesture Detector to detect a swipe from left gesture and do my actions accordingly.
if(!Platform.isIOS)
{
//When OS is Android return the view as is
return MyView;
}
else{
//When OS is iOS return the view as is wrapped with GestreDetector
return GestureDetector(
onHorizontalDragUpdate: (details) {
//set the sensitivity for your ios gesture anywhere between 10-50 is good
int sensitivity = Integers().iosSwipeSensitivity;
if (details.delta.dx > sensitivity) {
//SWIPE FROM RIGHT DETECTION
goBackward();
}
},
child: MyView;
);
}
Upvotes: 17