简体   繁体   中英

Android native Web View not working flutter

I am building a flutter app. I want to open webview from android native. I am calling the web using method channel. But when calling webview it showing error Attempt to invoke virtual method 'void android.webkit.WebView.loadUrl(java.lang.String)' on a null object reference

The code is shown below

main.dart

new RaisedButton(onPressed: ()async{
    final response=await channel.invokeMethod("WebView","");
        getRes(response);
    },
child:new Text("Go to Web View"))

and the java code is

MainActivity.java

public class MainActivity extends FlutterActivity {
private WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

            new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
    new MethodCallHandler() {
        @Override

            if (methodCall.method.equals("WebView")){
                Log.d("LOG","Entered in WebView ");
                webview.loadUrl("https://www.journaldev.com"); // Error is showing on here
            }
    });

        GeneratedPluginRegistrant.registerWith(this);
        webview2 = (WebView) findViewById(R.id.web_book1);

         }
    }

The error is showing in webview.loadUrl("https://www.journaldev.com"); line

web_view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <WebView
        android:id="@+id/web_book1"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentStart="false"
        android:layout_alignParentEnd="true" />


</RelativeLayout>

How to open android native WebView in flutter view. How it possible?

If you want to load an inline WebView inside the widget tree of your Flutter app or if you want to open an in-app browser, you can try my plugin flutter_inappbrowser ( EDIT : it has been renamed to flutter_inappwebview ).

An example is presented below (see the full example here ):

...

child: InAppWebView(
  initialUrl: "https://flutter.dev/",
  initialHeaders: {},
  initialOptions: InAppWebViewWidgetOptions(
      inAppWebViewOptions: InAppWebViewOptions(
        debuggingEnabled: true,
      )
  ),
  onWebViewCreated: (InAppWebViewController controller) {
    webView = controller;
  },
  onLoadStart: (InAppWebViewController controller, String url) {

  },
  onLoadStop: (InAppWebViewController controller, String url) {

  },
),

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM