Mixed support for Flutter web/mobile/desktop

Wonder whether you could extend the Dart client library with a factory class that returns an IServiceClient based upon the current target environment. Because it needs to switch between JsonWebClient and JsonServiceClient if you want to support all environments.

I currently use the following setup:

service_client_io.dart contains:

import 'package:servicestack/client.dart';
import 'package:servicestack/servicestack.dart';

class ServiceClientImpl {
  static IServiceClient create(String url) {
    return JsonServiceClient(url);
  }
}

service_client_web.dart contains:

import 'package:servicestack/web_client.dart';
import 'package:servicestack/servicestack.dart';

class ServiceClientImpl {
  static IServiceClient create(String url) {
    return JsonWebClient(url);
  }
}

and my real class service_client.dart has:

import 'service_client_web.dart' if (dart.library.io) 'service_client_io.dart';
import 'package:servicestack/servicestack.dart';

class ServiceClient {
  IServiceClient _client;

  ServiceClient(String url) {
    _client = ServiceClientImpl.create(url);
  }
}

This works as a charm, but would be nice if this is standard behavior of a servicestack dart file that returns a concrete implementation of the IServiceClient.

Your thoughts?

Yep good idea, I’ve added ClientFactory in this commit, e.g:

class ClientFactory
{
  static IServiceClient create([String baseUrl = "/"]) {
    var client = new JsonServiceClient(baseUrl);
    if (ClientConfig.initClient != null)  {
      ClientConfig.initClient(client);
    }
    return client;
  }
}

var client = ClientFactory.create();

As it’s a factory, I’ve also added the ability to configure all new IServiceClient instances, e.g you can configure Flutter/Web clients with the same JWT Token or API Key with:

ClientConfig.initClient = (client) => client.bearerToken = "...";

This change is available from v1.0.14 now on pub.

1 Like