1

I want to pass an optional List argument through go_router.
Here's my class with an optional List<int> argument:

class Loading extends StatefulWidget {
    List<int>? genres;
    Loading({Key? key, this.genres}) : super(key: key);

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

And the router:

final GoRouter _router = GoRouter(routes: [
    GoRoute(name: 'loading', path: '/', builder: (context, state) {
            List<int> genres = state.extra as List;
            return Loading(genres: genres);
        },  
    ), 

  ...
 
]);

But it doesn't work. I get this error message:

A value of type 'List<dynamic>' can't be assigned to a variable of type 'List<int>'.

How can I fix that?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Duddy67
  • 836
  • 2
  • 10
  • 26
  • hmmm, as far as i used go_router i havent actually encounter passing list, but have you tried? setting the List genres; to List in order to match up the data will allow go router to pass on states – Arbiter Chil Apr 06 '23 at 05:37

2 Answers2

2

Try casting the state.extra property to a List<int>.

final GoRouter _router = GoRouter(routes: [
    GoRoute(name: 'loading', path: '/', builder: (context, state) {
            List<int> genres = state.extra as List<int>? ?? [];
            return Loading(genres: genres);
        },  
    ),     
]);
gretal
  • 1,092
  • 6
  • 14
0

you can use mapper for pars data if sure it state.extra of list<int>

final GoRouter _router = GoRouter(routes: [
  GoRoute(name: 'loading', path: '/', builder: (context, state) {
    //This is a mapper
    List<dynamic> temp = state.extra as List<dynamic>;
    List<int> genres = temp.map((item) => item as int).toList();
    return Loading(genres: genres);
  },
  ),

  ...

]);
Javad Dehban
  • 1,282
  • 3
  • 11
  • 24
  • Thanks for your answer, but I get the following error message: `The method 'map' isn't defined for the class 'Object?'.` – Duddy67 Apr 06 '23 at 08:00
  • @Duddy67 What is the type `state.extra` ? – Javad Dehban Apr 06 '23 at 08:40
  • `state.extra.runtimeType` returns `Null` – Duddy67 Apr 06 '23 at 08:46
  • @Duddy67 https://stackoverflow.com/a/74813803/13600868 Check this page.then I edit my answer – Javad Dehban Apr 06 '23 at 08:52
  • 1
    It throws an exception: `The following _CastError was thrown building Builder(dirty): type 'Null' is not a subtype of type 'List' in type cast` I think Gretal's suggestion is is the way to go: `List genres = state.extra as List? ?? [];` – Duddy67 Apr 06 '23 at 09:14