Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.webviewflutter">
<uses-sdk android:minSdkVersion="20" android:targetSdkVersion="26"/>
</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package io.flutter.plugins.webviewflutter;

import static io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import static io.flutter.plugin.common.MethodChannel.Result;

import android.content.Context;
import android.view.View;
import android.webkit.WebView;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;

public class FlutterWebView implements PlatformView, MethodCallHandler {
private final WebView webView;
private final MethodChannel methodChannel;

FlutterWebView(Context context, BinaryMessenger messenger, int id) {
webView = new WebView(context);
methodChannel = new MethodChannel(messenger, "plugins.flutter.io/webview_" + id);
methodChannel.setMethodCallHandler(this);
}

@Override
public View getView() {
return webView;
}

@Override
public void onMethodCall(MethodCall methodCall, Result result) {
switch (methodCall.method) {
case "loadUrl":
loadUrl(methodCall, result);
break;
default:
result.notImplemented();
}
}

private void loadUrl(MethodCall methodCall, Result result) {
String url = (String) methodCall.arguments;
webView.loadUrl(url);
result.success(null);
}

@Override
public void dispose() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.flutter.plugins.webviewflutter;

import android.content.Context;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;

public class WebViewFactory extends PlatformViewFactory {
private final BinaryMessenger messenger;

public WebViewFactory(BinaryMessenger messenger) {
super(StandardMessageCodec.INSTANCE);
this.messenger = messenger;
}

@Override
public PlatformView create(Context context, int id, Object args) {
return new FlutterWebView(context, messenger, id);
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,14 @@
package io.flutter.plugins.webviewflutter;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** WebviewFlutterPlugin */
public class WebviewFlutterPlugin implements MethodCallHandler {
public class WebviewFlutterPlugin {
/** Plugin registration. */
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "webview_flutter");
channel.setMethodCallHandler(new WebviewFlutterPlugin());
}

@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
registrar
.platformViewRegistry()
.registerViewFactory(
"plugins.flutter.io/webview", new WebViewFactory(registrar.messenger()));
}
}
76 changes: 34 additions & 42 deletions packages/webview_flutter/example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,59 +2,51 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(new MyApp());
void main() => runApp(MaterialApp(home: new WebViewExample()));

class MyApp extends StatefulWidget {
class WebViewExample extends StatelessWidget {
@override
_MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';

@override
void initState() {
super.initState();
initPlatformState();
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView example'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[const SampleMenu()],
),
body: WebView(
onWebViewCreated: _onWebViewCreated,
),
);
}

// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await WebviewFlutter.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}

// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;

setState(() {
_platformVersion = platformVersion;
});
void _onWebViewCreated(WebViewController controller) {
controller.loadUrl('https://flutter.io');
}
}

class SampleMenu extends StatelessWidget {
const SampleMenu();

@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: new Center(
child: new Text('Running on: $_platformVersion\n'),
),
),
return PopupMenuButton<String>(
onSelected: (String value) {
Scaffold.of(context).showSnackBar(
new SnackBar(content: new Text('You selected: $value')));
},
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
const PopupMenuItem<String>(
value: 'Item 1',
child: Text('Item 1'),
),
const PopupMenuItem<String>(
value: 'Item 2',
child: Text('Item 2'),
),
],
);
}
}
109 changes: 104 additions & 5 deletions packages/webview_flutter/lib/webview_flutter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,112 @@

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

class WebviewFlutter {
static const MethodChannel _channel = MethodChannel('webview_flutter');
typedef void WebViewCreatedCallback(WebViewController controller);

static Future<String> get platformVersion async {
final String version = await _channel.invokeMethod('getPlatformVersion');
return version;
/// A web view widget for showing html content.
class WebView extends StatefulWidget {
/// Creates a new web view.
///
/// The web view can be controlled using a `WebViewController` that is passed to the
/// `onWebViewCreated` callback once the web view is created.
///
/// The `gestureRecognizers` parameter must not be null;
const WebView({
Key key,
this.onWebViewCreated,
this.gestureRecognizers = const <OneSequenceGestureRecognizer>[],
}) : assert(gestureRecognizers != null),
super(key: key);

/// If not null invoked once the web view is created.
final WebViewCreatedCallback onWebViewCreated;

/// Which gestures should be consumed by the web view.
///
/// It is possible for other gesture recognizers to be competing with the web view on pointer
/// events, e.g if the webview is inside a [ListView] the [ListView] will want to handle
/// vertical drags. The web view will claim gestures that are recognized by any of the
/// recognizers on this list.
///
/// When this list is empty, the web view will only handle pointer events for gestures that
/// were not claimed by any other gesture recognizer.
final List<OneSequenceGestureRecognizer> gestureRecognizers;

@override
State<StatefulWidget> createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
@override
Widget build(BuildContext context) {
if (defaultTargetPlatform == TargetPlatform.android) {
return new GestureDetector(
// We prevent text selection by intercepting long press event.
// This is a temporary workaround to prevent a native crash on a second
// text selection.
// TODO(amirh): remove this when the selection handles crash is resolved.
// https://github.com/flutter/flutter/issues/21239
onLongPress: () {},
child: AndroidView(
viewType: 'plugins.flutter.io/webview',
onPlatformViewCreated: _onPlatformViewCreated,
gestureRecognizers: widget.gestureRecognizers,
// WebView content is not affected by the Android view's layout direction,
// we explicitly set it here so that the widget doesn't require an ambient
// directionality.
layoutDirection: TextDirection.rtl,
),
);
}
return Text(
'$defaultTargetPlatform is not yet supported by the webview_flutter plugin');
}

void _onPlatformViewCreated(int id) {
if (widget.onWebViewCreated == null) {
return;
}
widget.onWebViewCreated(new WebViewController._(id));
}
}

/// Controls a [WebView].
///
/// A [WebViewController] instance can be obtained by setting the [WebView.onWebViewCreated]
/// callback for a [WebView] widget.
class WebViewController {
WebViewController._(int id) {
_channel = new MethodChannel(
'plugins.flutter.io/webview_$id', const StandardMethodCodec());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: StandardMethodCodec() is the default value

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

}

MethodChannel _channel;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can make this final MethodChannel _channel; by changing the constructor to:

WebViewController._(int id) : _channel = new MethodChannel(
        'plugins.flutter.io/webview_$id', const StandardMethodCodec());

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch


/// Loads the specified URL.
///
/// `url` must not be null.
///
/// Throws an ArgumentError if `url` is not a valid URL string.
Future<void> loadUrl(String url) async {
assert(url != null);
_validateUrlString(url);
return _channel.invokeMethod('loadUrl', url);
}
}

// Throws an ArgumentError if url is not a valid url string.
void _validateUrlString(String url) {
try {
final Uri uri = Uri.parse(url);
if (uri.scheme.isEmpty) {
throw new ArgumentError('Missing scheme in URL string: "$url"');
}
} on FormatException catch (e) {
throw new ArgumentError(e);
}
}
Loading