Go_Router Pass Object to new route

Use extra parameter in context.goNamed()

Example:

Object:

class Sample {
  String attributeA;
  String attributeB;
  bool boolValue;
  Sample(
      {required this.attributeA,
      required this.attributeB,
      required this.boolValue});}

Define GoRoute as

 GoRoute(
    path: '/sample',
    name: 'sample',
    builder: (context, state) {
      Sample sample = state.extra as Sample; // -> casting is important
      return GoToScreen(object: sample);
    },
  ),

Call it as:

Sample sample = Sample(attributeA: "True",attributeB: "False",boolValue: false)
context.goNamed("sample",extra:sample );

Receive it as:

class GoToScreen extends StatelessWidget {
  Sample? object;
  GoToScreen({super.key, this.object});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Text(
        object.toString(),
        style: const TextStyle(fontSize: 24),
      )),
    );
  }
}

Leave a Comment