如何使flutter webview只加载一次?

ulydmbyx  于 2022-11-25  发布在  Flutter
关注(0)|答案(1)|浏览(224)

当我从一个页面切换到另一个页面时,WebView的状态不会被记住,每次都会重新加载。如何防止这种情况?
我希望网页视图只在第一次加载时才能记住它的状态,但每次我导航到该屏幕时它都会重新加载。如何让它记住状态?

628mspwn

628mspwn1#

您可以使用PageViewAutomaticKeepAliveClientMixin来实现这一点。
查看此示例应用程序:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final bucket = PageStorageBucket();

  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  final PageController _controller = PageController();
  int _selectedIndex = 0;

  void _onItemTapped(int index) {
    setState(() {
      _controller.jumpToPage(index);
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: _selectedIndex,
          // selectedItemColor: Colors.amber[800],
          onTap: _onItemTapped,
          items: const [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: 'home'),
            BottomNavigationBarItem(icon: Icon(Icons.web), label: 'web'),
          ]),
      body: PageView(
        controller: _controller,
        children: const [MyDummyPage(), MyWebView()],
      ),
    );
  }
}

class MyDummyPage extends StatefulWidget {
  const MyDummyPage({super.key});

  @override
  State<MyDummyPage> createState() => _MyDummyPageState();
}

class _MyDummyPageState extends State<MyDummyPage>
    with AutomaticKeepAliveClientMixin {
  late int count;
  @override
  void initState() {
    super.initState();
    count = 0;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('$count'),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () => setState(() {
          count++;
        }),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class MyWebView extends StatefulWidget {
  const MyWebView({super.key});

  @override
  State<MyWebView> createState() => _MyWebViewState();
}

class _MyWebViewState extends State<MyWebView>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return const WebView(initialUrl: 'https://flutter.dev');
  }

  @override
  bool get wantKeepAlive => true;
}

相关问题