Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call a method in view I am directing to

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can pass arguments during pushed 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");
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading