skip to Main Content

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?

2

Answers


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