Skip to content

Instantly share code, notes, and snippets.

@iapicca
Created November 11, 2019 15:32
Show Gist options
  • Save iapicca/1ce2fd13658a88c28fb72facd5491bf7 to your computer and use it in GitHub Desktop.
Save iapicca/1ce2fd13658a88c28fb72facd5491bf7 to your computer and use it in GitHub Desktop.
KeepAlive mixin + WebView
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Key _key(int index) => Key(index.toString());
@override
Widget build(BuildContext context) => Scaffold(
body: ListView(
children: List<Widget>.generate(
5, (i) => WebViewKeepAlive(key:_key(i))),
),
);
}
class WebViewKeepAlive extends StatefulWidget {
final Key key;
WebViewKeepAlive({this.key});
@override
_WebViewKeepAlive createState() => _WebViewKeepAlive();
}
class _WebViewKeepAlive extends State<WebViewKeepAlive> with AutomaticKeepAliveClientMixin {
WebView _webView;
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
_webView = WebView(
initialUrl: "https://www.google.com/",
javascriptMode: JavascriptMode.unrestricted,
);
print('init'+widget.key.toString());
}
@override
void dispose() {
super.dispose();
_webView = null;
print('dispose'+widget.key.toString());
}
@override
Widget build(BuildContext context) {
super.build(context);
return Container(
height: 400,
child: _webView,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment