0

I need to pass a id parameter to a separate page while navigating from one page to another, I am currently using named routes to navigate but they are not letting me pass parameters.

1 Answers1

0

You have to use the "final" variable in the second route class and pass the values during instantiation of that class' object.

The below navigation example was obtained from Flutter docs I just added the "passing data to a new page" process.

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("First Route"),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text("Open route"),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      const SecondRoute(text: "This is the text")),
            );
          },
        ),
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  const SecondRoute({Key? key, required this.text}) : super(key: key);
  final String text;

  @override
  Widget build(BuildContext context) {
    print(text);
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Route"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text("Go back!"),
        ),
      ),
    );
  }
}
Dave
  • 15
  • 1
  • 7