I'm pretty new to Flutter so please forgive me if this is a basic question.
I'm trying to create a Flutter app that shows only a full screen webview but I need the device back button to go back in history. The first task I achieved with ease but the second is being a struggle.
I followed the instructions in this answer, but I couldn't remove all the clutter of a 360+ lines answer just to a back button and make it work.
My code is really simple:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(MyApp());
WebViewController _controller;
Future<void> _onWillPop(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
} else {
exit(0);
return Future.value(false);
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIOverlays([]);
return WillPopScope(
onWillPop: () => _onWillPop(context),
child: MaterialApp(title: 'Test App', home: WebView(
initialUrl: 'https://google.com',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController c) => _controller = c,
)),
);
}
}
But when I try to press the device back button, it throws the following error:
java.lang.RuntimeException: Cannot execute operation because FlutterJNI is not attached to native.
at io.flutter.embedding.engine.FlutterJNI.ensureAttachedToNative(FlutterJNI.java:227)
at io.flutter.embedding.engine.FlutterJNI.markTextureFrameAvailable(FlutterJNI.java:554)
at io.flutter.embedding.engine.renderer.FlutterRenderer.markTextureFrameAvailable(FlutterRenderer.java:274)
at io.flutter.embedding.engine.renderer.FlutterRenderer.access$300(FlutterRenderer.java:38)
at io.flutter.embedding.engine.renderer.FlutterRenderer$SurfaceTextureRegistryEntry$1.onFrameAvailable(FlutterRenderer.java:145)
at android.graphics.SurfaceTexture$1.handleMessage(SurfaceTexture.java:211)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
There are at least 3 threads on flutter's github but none of the solutions worked for me. what am I missing here?