Home > Enterprise >  Get Route arguments through BuildContext requires putting it inside build()?
Get Route arguments through BuildContext requires putting it inside build()?

Time:11-25

From https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments it appears the preferred way of getting the arguments from a route is using:

ModalRoute.of(context)!.settings.arguments;

But since it requires the context argument it must be called inside the build method:

Widget build(BuildContext context) {
  String id = ModalRoute.of(context)!.settings.arguments as String;
  var data = httpGet(id);
  return Scaffold(
    //...
  );
}

This means that every time the widget is rebuilt, the route argument will be refetched all over again and possibly another network call too.

The obvious solution is to have a boolean like wasFetched somewhere and add a conditional inside the build method.

Maybe a more elegant solution is to split the widget into 2 widgets and nest 1 inside the other.

Are most people doing the latter?

CodePudding user response:

You can call it only once per widget initialisation by moving it to your initState() and scheduling a post frame so it only accesses BuildContext after rendering.

@override
void initState() {
    WidgetsBinding.instance.addPostFrameCallback(() {
      String id = ModalRoute.of(context)!.settings.arguments as String;
      var data = httpGet(id);
    });
}

CodePudding user response:

You can actually access context in your initState method without having to pass it as a parameter.

class _YourScreenState extends State<YourScreen> {
 late String id;

 @override
 void initState() {
   super.initState();
   id = ModalRoute.of(context)!.settings.arguments as String;
 }
}
  • Related