Home > Back-end >  Is there a way to call a method every time revisit the screen in bottom nav bar?
Is there a way to call a method every time revisit the screen in bottom nav bar?

Time:01-22

I need to call a method every time I revisit that tab in the bottom NAV Bar. I use Persistent Bottom Navigation Bar package.

Currently, I call that method in the initState and it only gets called once when the page first loads up. But I want it to be called every time I change to this tab from another tab.

Is there a way to do this?

Home Screen - Method that need to be called

CodePudding user response:

Okay, it's not my best work, but I think it accomplishes the goal. It does leverage another package, visibility_detector

Install:

dependencies:
  visibility_detector: ^0.2.2

Import the package:

import 'package:visibility_detector/visibility_detector.dart';

Listen for changes in visibility:

// Stateless
class ExploreScreen extends StatelessWidget {
  const ExploreScreen({Key? key}) : super(key: key);
  static String id = 'exploreScreen';

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: Key(ExploreScreen.id),
      onVisibilityChanged: (VisibilityInfo info) {
        bool isVisible = info.visibleFraction != 0;
        callThisMethod(isVisible);
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Explore Screen'),
        ),
        body: ... 
      ),
    );
  }
  void callThisMethod(bool isVisible){
    debugPrint('ExploreScreen.callThisMethod: isVisible: ${isVisible}');
  }
}

// Stateful
class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
    // callThisMethod(); // Note I commented this out, for _my_ test. You might decide you want it
  }
  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: Key(HomeScreen.id),
      onVisibilityChanged: (VisibilityInfo info) {
        bool isVisible = info.visibleFraction != 0;
        callThisMethod(isVisible);
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Home Screen'),
        ),
        body: ... ,
      ),
    );
  }
  void callThisMethod(bool isVisible){
    debugPrint('_HomeScreenState.callThisMethod: isVisible: ${isVisible}');
  }
}

CodePudding user response:

override didChangeDependencies and add your function call in it

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    callThisMethod();
  }
  •  Tags:  
  • Related