LoginSignup
3
2

More than 1 year has passed since last update.

【Flutter】WebViewをPageViewやTabBarViewで状態を保持しながら切り替える

Posted at

ソースコード

※ WebView には flutter_inappwebview パッケージを使用。

課題

PageViewやTabBarViewでWebViewを表示している際、WebViewのページ(またはタブ)を表示するたびにロードが走ってしまう。
→ Webページの状態(スクロール位置や表示内容)が保持できない。

解決策

こちらのQAを参考にした。

WebViewをAutomaticKeepAliveClientMixinをmixinしたWidgetとすることで、ページやタブ切り替え時にも状態が保持できるようになる。

AutomaticKeepAliveClientMixinをmixinしたWebView
class KeepAliveWebPage extends StatefulWidget {
  const KeepAliveWebPage(this.url, {Key? key}) : super(key: key);

  final String url;

  @override
  State<KeepAliveWebPage> createState() => _KeepAliveWebPageState();
}_

class _KeepAliveWebPageState extends State<KeepAliveWebPage>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return InAppWebView(
      initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
PageViewの書き方は通常の使い方通り
class PageWebView extends StatefulWidget {
  const PageWebView({Key? key}) : super(key: key);

  @override
  State<PageWebView> createState() => _PageWebViewState();
}

class _PageWebViewState extends State<PageWebView> {
  final _controller = PageController();

  int _currentPageIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page: $_currentPageIndex'),
      ),
      body: PageView(
        controller: _controller,
        children: const [
          KeepAliveWebPage("https://flutter.dev/"),
          KeepAliveWebPage("https://www.nintendo.co.jp/"),
          KeepAliveWebPage("https://www.playstation.com/ja-jp/"),
        ],
        onPageChanged: (int pageIndex) {
          setState(() {
            _currentPageIndex = pageIndex;
          });
        },
      ),
    );
  }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2