Home > Enterprise >  How to check whether a screen is already created on the stack in Flutter?
How to check whether a screen is already created on the stack in Flutter?

Time:03-22

Let's say I have a Bottom Nav Bar as below, and I have used Navigator.pushNamed in in viewing those screens through onClick.

Example Bottom Nav Bar

What I want to know is rather than having the Navigator.pushNamed on each of the button clicks in the NavBar buttons to navigate through the pages, is there a technique that can be used before executing the Navigator.pushNamed command to see whether there is an instance of the screen already created in the stack so that I can use the Navigator.popUntil method to have better performance.

CodePudding user response:

I would use a try catch block to see if you could pop the context. Other way, I don't think that with the use of a bottom Nav Bar, us should create a howl new screen for every navigation item. Instead, I would create a body widget for every Navigator item and only change the body as long as the Nav Bar should be shown. This way is the most efficient way to work with the Nav Bar.

CodePudding user response:

You can use Tabbar widget in bottom navigation bar. I hope it will solve your current concerns.

import 'package:flutter/material.dart';

void main() {
  runApp(const TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  const TabBarDemo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Tabs Demo'),
          ),
          bottomNavigationBar: const TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car, color: Colors.black)),
                Tab(icon: Icon(Icons.directions_transit, color: Colors.black)),
                Tab(icon: Icon(Icons.directions_bike, color: Colors.black)),
              ],
          ),
          body: const TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}
  • Related