Victor
Victor

Reputation: 63

How to maintain Webview state with BottomNavigationBar in Flutter

I'm creating a Flutter application that uses a BottomNavigationBar to change between pages. In one of the pages, I have a Webview (I'm using the plugin developed by the Flutter dev team) and I can't get to keep the state of the webview when I navigate to another tab then come back. I don't know if there is a way either.

I've tried using a PageStorageBucket and also AutomaticKeepAliveClientMixin, to no avail. I've noticed that the state of a simple ListView is kept between tabs when using PageStorageBucket, but it doesn't seem to work with a Webview.

Here's a minimal, reproducible example:

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> _pages;
  int _selectedIndex = 0;

  @override
  void initState() {
    super.initState();
    _pages = [
      Center(
        child: Text('HOME'),
      ),
      WebView(
        initialUrl: 'https://flutter.io',
        javascriptMode: JavascriptMode.unrestricted,
      )
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
          BottomNavigationBarItem(icon: Icon(Icons.web), title: Text('Web')),
        ],
        currentIndex: _selectedIndex,
        onTap: (index) {
          setState(() {
            _selectedIndex = index;
          });
        },
      ),
      body: _pages[_selectedIndex],
    );
  }

https://i.sstatic.net/Ge1W6.jpg

I'd want the web to be in the same state when I go back to the Webview tab, I don't want it to reload.

Upvotes: 5

Views: 2083

Answers (2)

Victor
Victor

Reputation: 63

Well, after some digging, I managed to find a solution.

Instead of using BottomNavigationBar, I used TabBar (in the bottomNavigationBar Scaffold field).

Combining this with AutomaticKeepAliveClientMixin, the tabs don't unload and the state is kept through tab changes.

Upvotes: 1

RegularGuy
RegularGuy

Reputation: 3676

You could use an IndexedStack for this. it will never unload the children. However , it will load them at all once [producing a little lag]

    body:IndexedStack(
              index: _selectedIndex ,
              children: <Widget>[
               FirstPage(),
               Webview(),
               //etc...
              ]
            ),

Upvotes: 4

Related Questions