How can I navigate between 2 classes, one of them requires passing data? in flutter

you can use constructor but in this case, whenever you use this class, you have to provide value, also you can make class value nullable and check it on build time. Another way is passing data by Route.

for more navigate-with-arguments

Here are is example:

Passing data using ModalRoute

  Navigator.of(context).push(
                  MaterialPageRoute(
                      builder: (context) => WidgetA(),
                      settings: RouteSettings(
                        arguments: "Data for A",
                      )),
                );

Receive Data

class WidgetA extends StatelessWidget {
  static final routeName = "/widgetA";
  @override
  Widget build(BuildContext context) {
    final data = ModalRoute.of(context)!.settings;

    late String retriveString;

    if (data.arguments == null)
      retriveString = "empty";
    else
      retriveString = data.arguments as String;

    return Scaffold(
      body: Column(
        children: [
          Text("Widget A"),
          Text("Got data from parent $retriveString"),
        ],
      ),
    );
  }
}

Passing Emptydata using ModalRoute

 Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => WidgetB(),
                  ),
                );

On Receiver side


class WidgetB extends StatelessWidget {
  static final routeName = "/widgetB";
  @override
  Widget build(BuildContext context) {
  
    return Scaffold(
      body: Column(
        children: [
          Text("Widget B"),
        ],
      ),
    );
  }
}

Passing data using Constructor
must provide while using widget.

 Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => WidgetC(data: "for C"),
                  ),
                );

Receiver

class WidgetC extends StatelessWidget {
  final String data;

  const WidgetC({Key? key, required this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [Text("Widget C "), Text("data using Constructor: $data")],
      ),
    );
  }
}

Passing data(optional) using Constructor

Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => WidgetD(),
                  ),
                );

Receiver


class WidgetD extends StatelessWidget {
  final String? data;

  WidgetD({Key? key, this.data = ""}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Text("Widget D nullable "),
          Text("data using Constructor: $data")
        ],
      ),
    );
  }
}

Leave a Comment