Search code examples
flutterdartmemoryreference

Dart / Flutter and REST client


I'm not proficient with Dart's memory model. In my app, I create a client to talk to a REST api, and I pass this client to several widgets. This client handles tokens (as attributes) to authenticate with the API.

  @override
  void initState() {
    super.initState();
    _widgetOptions = <Widget>[
      MyAwesomeWidget(client: widget.client),
      MyWidget(client: widget.client),
      SettingsPage(client: widget.client)
    ];
  }

The SettingsPage widget contains a logout button that nullifies the tokens held by the client. At this point, I'm expecting the client to be unusable by all the widget with a reference to it (don't worry, I have code to handle this case in all the widgets). Am I right here? Or is the client somehow copied into the other widgets?


Solution

  • If the token data member is defined inside the client, and is not copied externally by the consumer widgets, then it will behave as you expect.

    • If you're only invalidating the token client side (maybe to return the same token later), make sure it is properly encapsulated.
    • If you're invalidating the token server-side, then your consumer widgets should handle failing API requests.

    As for the Dart memory model:

    "Primitives (like int, bool, and num) are passed by value. Objects are passed by reference. This is the same behavior as in Java for passing arguments." - Emily Fortuna