How to Call Method in One Stateful Widget From Another Stateful Widget In Flutter

How to Call Method in One Stateful Widget From Another Stateful Widget In Flutter??

A Stateful Widget will maintain data and will react accordingly to whatever the data is doing within the mobile application. A Stateful Widget is a mutable widget that is the reason it can be drawn multiple times within its lifetime. So in this article, We will go through How to Call Method in One Stateful Widget From Another Stateful Widget In Flutter.

How to Call Method in One Stateful Widget From Another Stateful Widget In Flutter?

First, you need to know how to call function in flutter? To call a function of a parent, you can use the callback pattern. In this example, a function on the color selected is passed to the child. The child calls the function when a button is pressed:

import 'package:flutter/material.dart';

class Parent extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ParentState();
  }
}

class ParentState extends State<Parent> {
  Color selectedColor = Colors.grey;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          color: selectedColor,
          height: 200.0,
        ),
        ColorPicker(
          onColorSelect: (Color color) {
            setState(() {
              selectedColor = color;
            });
          },
        )
      ],
    );
  }
}

class ColorPicker extends StatelessWidget {
  const ColorPicker({this.onColorSelect});

  final ColorCallback onColorSelect;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        RaisedButton(
          child: Text('red'),
          color: Colors.red,
          onPressed: () {
            onColorSelect(Colors.red);
          },
        ),
        RaisedButton(
          child: Text('green'),
          color: Colors.green,
          onPressed: () {
            onColorSelect(Colors.green);
          },
        ),
        RaisedButton(
          child: Text('blue'),
          color: Colors.blue,
          onPressed: () {
            onColorSelect(Colors.blue);
          },
        )
      ],
    );
  }
}
typedef ColorCallback = void Function(Color color);

Internal Flutter widgets like buttons or form fields use exactly the same pattern. Do you know how to call function in a flutter? If you only want to call a function without any arguments, you can use the VoidCallback type instead of defining your own callback type.

class ColorPickerWrapper extends StatelessWidget {
  const ColorPickerWrapper({this.onColorSelect});

  final ColorCallback onColorSelect;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(20.0),
      child: ColorPicker(onColorSelect: onColorSelect),
    )
  }
}

Calling a method of a child widget from a parent widget is discouraged in Flutter. Instead, Flutter encourages you to pass down the state of a child as constructor parameters. Hence instead of calling a method of the child, you just call setState in the parent widget to update its children.

One alternative approach is the controller classes in Flutter (ScrollController, AnimationController, …). These are also passed to the children as constructor parameters, and they contain methods to control the state of the child without calling setState on the parent.

Example:

scrollController.animateTo(200.0, duration: Duration(seconds: 1), curve: Curves.easeInOut);

The children are then required to listen to these changes to update their internal state. Of course, you can also implement your own controller class. If you need to, I recommend you to look at the source code of Flutter to understand how that works.

You can do that by using the key of the widget

class MyWidget extends StatefulWidget {

      const MyWidget ({Key key}) : super(key: key);

      @override
      State<StatefulWidget> createState()=> MyState();


    }

   class MyState extends State<MyWidget >{



      Widget build(BuildContext context){ return ....}

      void printSample (){
         print("Sample text");
      }

 }

now when use MyWidget declares GlobalKey as a global key.

GlobalKey<MyState> _myKey = GlobalKey();

and pass it when creating a widget

MyWidget(
key : _myKey,
)

by this key, you can call any public method inside the state.

_myKey.currentState.printSample();

You can give this a try, it will call a method defined on Page2 (StatefulWidget) from Page1 (StatefulWidget) Widget.

class Page1 extends StatefulWidget {
  @override
  _Page1State createState() => _Page1State();
}

class _Page1State extends State<Page1> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          child: Text("Call page 2 method"),
          onPressed: () => Page2().method(),
        ),
      ),
    );
  }
}

class Page2 extends StatefulWidget {
  method() => createState().methodInPage2();

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

class _Page2State extends State<Page2> {
  methodInPage2() => print("method in page 2");

  @override
  Widget build(BuildContext context) => Container();
}

Conclusion:

In this article, We have been through the How to Call Method in One Stateful Widget From Another Stateful Widget In Flutter ??

Thanks for being with us on a Flutter Journey !!!

Keep Learning !!! Keep Fluttering !!!

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields