0

In a named route navigation I need to pass some arguments, but on destination the value is null. Here my code:

onSelected: (value){
    Navigator.pushNamed(context, '${value['namedRoute']}', arguments: '${value['apiUrl']}');
  },

On the destination screen I have:

class DetailList extends StatefulWidget {
  final String apiUrl;

  DetailList({Key key, @required this.apiUrl,}) : super(key: key);

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

class _DetailList extends State<DetailList> {
  final Color bgcolor = HexToColor('#ffffff');

  ApiResponse<List<Detail>> detailList;
  int countDetails = 0;

  DetailListBloc _detailListBloc;

  @override
  void initState() {
    print('init=${widget.apiUrl}');

    super.initState();
    _detailListBloc = DetailListBloc(widget.apiUrl);
  }
  .....

Here the print output is 'init=null'. I do not know where the problem is as I followed this link. Any help will be appreciated.

EDIT

Thank you for all your help. I found this link which describes exactly what I was looking for and it works like a charm.

cwhisperer
  • 1,478
  • 1
  • 32
  • 63

1 Answers1

0

That's not how you extract the argument, here is how:

  @override
  void initState() {
    print('init=${ModalRoute.of<String>(context).settings.arguments}');

    super.initState();
    _detailListBloc = DetailListBloc(widget.apiUrl);
  }

see reference

Edit: because context might not be ready instantly in initState() and according to this you can use:

@override
  void initState(){
    Future.delayed(Duration.zero,(){//you can await it if you want
      print('init=${ModalRoute.of<String>(context).settings.arguments}');
      _detailListBloc = DetailListBloc(widget.apiUrl);  
    });
    super.initState();
  }
HII
  • 3,420
  • 1
  • 14
  • 35
  • ok, but I need the argument in the initState(). Could you please show me where to put this part of code ? – cwhisperer Apr 23 '20 at 12:38
  • you can put it anywhere inside the newly pushed widget, i will edit the answer – HII Apr 23 '20 at 12:39
  • This is the error I receive: The following assertion was thrown building Builder: dependOnInheritedWidgetOfExactType<_ModalScopeStatus>() or dependOnInheritedElement() was called before _DetailList.initState() completed. – cwhisperer Apr 23 '20 at 12:44