Call a method in view I am directing to

Issue

I have a deeply nested view where I am not capable to pass this method through callback. Are there any ways that I can call a method inside a class that I am pushing to?

For e.g Navigator.pushNamed(context, "/main"); and the view main has a method inside it that should be called instantly when navigating to. In javascript there is something like an event bus where I am able to trigger a method anywhere in my app from specific deeply nested view. Are there things in flutter/dart that could help me achieve this?

Solution

You can pass arguments during push and check the argument in the pushed view’s initState.

Navigator.pushNamed(
  context,
  "/main",
  arguments: {'call_method_2': true},
);

Main (Widget)

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

class Main extends StatefulWidget {
  const Main({Key? key}) : super(key: key);

  @override
  State<Main> createState() => _MainState();
}

class _MainState extends State<Main> {

  @override
  void initState() {
    final arguments = (ModalRoute.of(context)?.settings.arguments ?? <String, dynamic>{}) as Map;

    if(arguments['call_method_2'] == true) {
      method2();
    } else {
      method1();
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  void method1() {
    log("method1");
  }

  void method2() {
    log("method2");
  }
}

Answered By – Zakaria Hossain

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.