flutterdio

How do I add a value to the data object from inside a Dio interceptor


I am using Dio in my Flutter application and I am attempting to add a value into the body object for all http requests. In some instances the options -> data object will be non existent and I create it inside the interceptor with my key/value. That works fine. Howere on POST requests which already have a body of key/values I am attempting to add it and it will not work. There are no errors, the code just stops at the line where I am attempting to add the key/value to the Map.

Lol i feel like this should be simple. I have tried many things in terms of syntax tweaks, but I am really not understanding why this won't work.

..interceptors.add(
  InterceptorsWrapper(
    onRequest: (options, handler) async {
      final role = storage.readRole();

      if (role?.id != null && options.data == null) {
        options.data = {"channelId": role?.id};
      }

      if (role?.id != null && options.data != null) {
        // code stops here
        options.data["channelId"] = role?.id;
      }

      return handler.next(options);
    },
  ),
)

To be clear I am trying to add the key/value channelId to the body object.


Solution

  • Make sure that options.data is an actual Map

    I suspect that it has already been initialised but not as a Map.