skip to Main Content

I want to pass a map of complex data as a parameter to a GoRoute(). However, from what I can see, the param is a String. I tried converting my Map -> String, but it immediately causes all sorts of errors due to format errors: Unexpected character (at character 2).

Im most likely going about this the incorrect way.

Is it even possible to send a Map of data as a parameter in GoRouter?

2

Answers


  1. Chosen as BEST ANSWER

    It can be done, but JsonEncode and then JsonDecode on the other side, I have performed it incorrectly


  2. I would suggest you to use Model and have toJson() fromJson() methods. And pass between routes as Model using extra.


    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),
          )),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search