How to Finish Current View/Activity In Flutter?

· 2 min read
How to Finish Current View Activity In Flutter
How to Finish Current View Activity In Flutter

The native android mobile application provides this. finish()  to finish the current flutter activity, so in this article, we will go through How to  Finish Current View / Activity In Flutter.

Let’s get into the same.

How to Finish Current View / Activity In Flutter ??

If the user wishes to close the current screen and come back to the previous screen? If that, Navigator.pop(context) should do the work. However, if you are at the entry screen (the first screen of the app and this screen has no parent screen/previous screen), Navigator. pop(context) will return you to a black screen. In this case, we have to use SystemNavigator.pop().

The below code will work on Android for both cases:

if (Navigator.canPop(context)) {
  Navigator.pop(context);
} else {
  SystemNavigator.pop();
}

Use Navigator.pushReplacement(BuildContext context, Route<T> newRoute) to open a new route that replaces the current route of the navigator.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('My App'),
        backgroundColor: Colors.blue,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FlatButton(
                color: Colors.blue,
                child: const Text(
                  'Flat Button',
                  style: TextStyle(fontSize: 20),
                ),
                onPressed: () {
                  if (Navigator.canPop(context)) {
                    Navigator.pop(context);
                  } else {
                    SystemNavigator.pop();
                  }
                }),
          ],
        ),
      ),
    );
  }

Output

How to Finish Current View/Activity In Flutter

Conclusion:

Thanks for being with us on a Flutter Journey !!!

In this article, we have been through How to Finish Current View / Activity In Flutter ??

Keep Learning !!! Keep Fluttering !!!

The Flutter Agency a leading Flutter development company offers solutions through development support, technology updates, news, tips, and how-to articles. Get hundreds of supportive articles and useful resources on our platform.

Leave a Reply