DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Publishing Flutter Packages to JFrog Artifactory
  • Guide for Voice Search Integration to Your Flutter Streaming App
  • Why Choose Flutter App Development When You Need a Mobile App
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks

Trending

  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  • The Role of Functional Programming in Modern Software Development
  • Teradata Performance and Skew Prevention Tips
  • Understanding Java Signals
  1. DZone
  2. Coding
  3. Frameworks
  4. Handling Flutter Webview Back-Button

Handling Flutter Webview Back-Button

By 
Omer Yilmaz user avatar
Omer Yilmaz
DZone Core CORE ·
Updated Feb. 19, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
28.7K Views

Join the DZone community and get the full member experience.

Join For Free

In my previous article, I introduced how to implement Flutter Webview URL Listeners to your flutter applications.

Now, we need to add functionality to navigate through the website with the back button. Currently, instead of going back, our application gets closed. To prevent this, we need to add an operation check to see whether the webview can go back, and if it can, then, we need to load the webview of previous pages.

Step 1

To get a callback when we press the back button, we need to wrap our view inside WillPopScope and create a method inside _WebViewWebPageState to check if webview can go back. If it can, then we perform the back operation. Otherwise, we'll show exit dialog.

Dart
 




x
43


 
1
 
          
2
 Future<bool> _onBack() async {
3
 bool goBack;
4
 var value = await webView.canGoBack();  // check webview can go back 
5
 if (value) {
6
   webView.goBack(); // perform webview back operation
7
   return false;
8
 } else {
9
   await showDialog(
10
     context: context,
11
     builder: (context) => new AlertDialog(
12
       title: new Text('Confirmation ', style: TextStyle(color: Colors.purple)),
13
       // Are you sure?
14
       content: new Text('Do you want exit app ? '),
15
       // Do you want to go back?
16
       actions: <Widget>[
17
         new FlatButton(
18
           onPressed: () {
19
             Navigator.of(context).pop(false);
20
             setState(() {
21
               goBack = false;
22
             });
23
           },
24
           child: new Text('Yes'), // No
25
         ),
26
         new FlatButton(
27
           onPressed: () {
28
             Navigator.of(context).pop();
29
             setState(() {
30
               goBack = true;
31
             });
32
           },
33
           child: new Text('No'), // Yes
34
         ),
35
       ],
36
     ),
37
   );
38
 
          
39
   if (goBack) Navigator.pop(context);   // If user press Yes pop the page
40
   return goBack;
41
 }
42
}
43
 
          



You may also like: Core Dart

Step 2

Create one webview variable inside _WebViewWebPageState and assign its value inside the onWebViewCreated method.

Dart
 




xxxxxxxxxx
1


 
1
onWebViewCreated: (InAppWebViewController controller) {
2
 webView = controller;
3
}
4
 
          



Now, run the application, and it will be responsive to the back button operation. The final code will look like the following screenshot. ( File: ProjectRoot/webviewapp/lib/SecondPage.dart )

Back button example


Exit page confirmation

Exit page confirmation


Dart
 




xxxxxxxxxx
1
144


 
1
import 'package:flutter/material.dart';
2
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
3
import 'package:webviewapp/SecondPage.dart';
4
 
          
5
void main() => runApp(MyApp());
6
 
          
7
class MyApp extends StatelessWidget {
8
 // This widget is the root of your application.
9
 @override
10
 Widget build(BuildContext context) {
11
   return MaterialApp(
12
     title: 'Flutter Demo',
13
     theme: ThemeData(
14
       primarySwatch: Colors.blue,
15
     ),
16
     home: WebViewWebPage(),
17
   );
18
 }
19
}
20
 
          
21
class WebViewWebPage extends StatefulWidget {
22
 @override
23
 _WebViewWebPageState createState() => _WebViewWebPageState();
24
}
25
 
          
26
class _WebViewWebPageState extends State<WebViewWebPage> {
27
 
          
28
 Future<bool> _onBack() async {
29
   bool goBack;
30
   var value = await webView.canGoBack();  // check webview can go back
31
   if (value) {
32
     webView.goBack(); // perform webview back operation
33
     return false;
34
   } else {
35
     await showDialog(
36
       context: context,
37
       builder: (context) => new AlertDialog(
38
         title: new Text('Confirmation ', style: TextStyle(color: Colors.purple)),
39
         // Are you sure?
40
         content: new Text('Do you want exit app ? '),
41
         // Do you want to go back?
42
         actions: <Widget>[
43
           new FlatButton(
44
             onPressed: () {
45
               Navigator.of(context).pop(false);
46
               setState(() {
47
                 goBack = false;
48
               });
49
             },
50
             child: new Text(No), // No
51
           ),
52
           new FlatButton(
53
             onPressed: () {
54
               Navigator.of(context).pop();
55
               setState(() {
56
                 goBack = true;
57
               });
58
             },
59
             child: new Text(Yes), // Yes
60
           ),
61
         ],
62
       ),
63
     );
64
 
          
65
     if (goBack) Navigator.pop(context);   // If user press Yes pop the page
66
     return goBack;
67
   }
68
 }
69
 
          
70
 
          
71
 // URL to load
72
 var URL = "https://google.com.tr";
73
 
          
74
 var LISTENINGURL = "https://www.linkedin.com/in/omeryilmaz86/";
75
 
          
76
 // Webview progress
77
 double progress = 0;
78
 InAppWebViewController webView;
79
 
          
80
 @override
81
 Widget build(BuildContext context) {
82
   return WillPopScope(
83
     onWillPop: _onBack,
84
     child: Scaffold(
85
         appBar: AppBar(
86
           title: Text("Webview App"),
87
         ),
88
         body: Container(
89
             child: Column(
90
                 children: <Widget>[
91
           (progress != 1.0)
92
               ? LinearProgressIndicator(
93
                   value: progress,
94
                   backgroundColor: Colors.grey[200],
95
                   valueColor: AlwaysStoppedAnimation<Color>(Colors.purple))
96
               : null,    // Should be removed while showing
97
           Expanded(
98
             child: Container(
99
               child: InAppWebView(
100
                 initialUrl: URL,
101
                 initialHeaders: {},
102
                 initialOptions: {},
103
                 onWebViewCreated: (InAppWebViewController controller) {
104
                   webView = controller;
105
                 },
106
                 onLoadStart: (InAppWebViewController controller, String url) {
107
                   // Listen Url change
108
                   if(URL == LISTENINGURL){
109
                     Navigator.of(context, rootNavigator: true)
110
                         .push(MaterialPageRoute(
111
                         builder: (context) => new SecondPage()));
112
                   }
113
                 },
114
                 onProgressChanged:
115
                     (InAppWebViewController controller, int progress) {
116
                   setState(() {
117
                     this.progress = progress / 100;
118
                   });
119
                 },
120
               ),
121
             ),
122
           )
123
         ].where((Object o) => o != null).toList()))),
124
   );  //Remove null widgets
125
 }
126
}
127
 
          
128
 
          
129
class SecondPage extends StatelessWidget {
130
 @override
131
 Widget build(BuildContext context) {
132
   return Scaffold(
133
     appBar: AppBar(
134
       title: Text("Second Page"),
135
     ),
136
     body: Container(
137
       child: Center(
138
         child: Text("Hey,there!"),
139
       ),
140
     ),
141
   );
142
 }
143
}
144
 
          


Flutter (software)

Opinions expressed by DZone contributors are their own.

Related

  • Publishing Flutter Packages to JFrog Artifactory
  • Guide for Voice Search Integration to Your Flutter Streaming App
  • Why Choose Flutter App Development When You Need a Mobile App
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!