Last active
May 10, 2021 13:57
-
-
Save GAM3RG33K/ee62f1d921e25536bdd3e3e91470ea9f to your computer and use it in GitHub Desktop.
[Flutter] How to use basic features of web view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Future<void> _showDemoPage(BuildContext context, String url) async { | |
final parameters = await Navigator.of(context).push( | |
MaterialPageRoute( | |
builder: (context) => CustomWebView( | |
initialUrl: url, | |
), | |
), | |
); | |
print('AppHome: _showDemoPage: parameters: $parameters'); | |
} | |
} | |
class CustomWebView extends StatefulWidget { | |
final String initialUrl; | |
const CustomWebView({Key key, this.initialUrl}) : super(key: key); | |
@override | |
_CustomWebViewState createState() => _CustomWebViewState(); | |
} | |
class _CustomWebViewState extends State<CustomWebView> { | |
bool _showProgress = false; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: SafeArea( | |
child: SingleChildScrollView( | |
child: Column( | |
crossAxisAlignment: CrossAxisAlignment.start, | |
children: [ | |
Offstage( | |
offstage: !_showProgress, | |
child: LinearProgressIndicator(), | |
), | |
SizedBox( | |
height: 800, | |
child: buildWebView(), | |
), | |
], | |
), | |
), | |
), | |
); | |
} | |
Widget buildWebView() { | |
return InAppWebView( | |
initialUrlRequest: URLRequest( | |
url: Uri.parse(widget.initialUrl), | |
), | |
onLoadStart: (controller, url) => _onPageStart(url.toString()), | |
onLoadStop: (controller, url) => _onPageFinish(url.toString()), | |
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[ | |
Factory<OneSequenceGestureRecognizer>( | |
() => HorizontalDragGestureRecognizer(), | |
), | |
].toSet(), | |
); | |
} | |
void setProgressBar(bool status) { | |
setState(() => _showProgress = status); | |
} | |
void _onPageStart(String url) { | |
print('_CustomWebViewState: _onPageStart: url: $url'); | |
// [optional] method to extract data from current url | |
// final params = _extractParams(url); | |
// Navigator.of(context).pop(params); | |
setProgressBar(true); | |
} | |
void _onPageFinish(String url) { | |
print('_CustomWebViewState: _onPageFinish: url: $url'); | |
setProgressBar(false); | |
} | |
// method to extract parameters from current url | |
_extractParams(String url) { | |
final paramString = url.substring(url.indexOf('?') + 1); | |
final params = {}; | |
paramString.split('&').forEach((String _param) { | |
final entry = _param.split('='); | |
final key = entry[0]; | |
final value = entry[1]; | |
params[key] = value; | |
}); | |
print('_CustomWebViewState: _onPageFinish: params: $params'); | |
return params; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment