Ad

Call Navigator From Outside State Or Call Child State Method From Parent

- 1 answer

I ended up with a parent calling a child method, which is fine, but I can't call Navigator outside the state class. My goal is either to move the child method in it's state and somehow access it, or to call Navigator form outside the state in a Stateful widget.

What is the best approach to this problem?

import 'package:flutter/material.dart';

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

  @override
  _ParentClassState createState() => _ParentClassState();
}

class _ParentClassState extends State<ParentClass> {
  ChildClass childclass = ChildClass();
  @override
  Widget build(BuildContext context) {
    return Container(
      child: ElevatedButton(
          child: Text('Button'),
          onPressed: () => {
                childclass.callNavigator(),//or call callNavigatorState
              }),
    );
  }
}

class ChildClass extends StatefulWidget {
  const ChildClass({Key? key}) : super(key: key);
  void callNavigator() {
    //call navigator from here
  }
  @override
  _ChildClassState createState() => _ChildClassState();
}

class _ChildClassState extends State<ChildClass> {
  void callNavigatorState(){
    //access from parent widget?
  }
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Ad

Answer

you can access a stateful's state, using Globalkey.currentState...

check this sample code:

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

  final child = ChildWidget(key: GlobalKey());
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          child,
          ElevatedButton(
              onPressed: () {
                (((child as ChildWidget).key as GlobalKey).currentState!
                        as _ChildWidgetState)
                    .someFunction();
              },
              child: Text("childWidget someFunction"))
        ],
      ),
    );
  }
}

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

  @override
  _ChildWidgetState createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  void someFunction() {
    print("childWidget someFunction");
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Ad
source: stackoverflow.com
Ad