Closed dedvalson closed 4 years ago
As far as I know you can't mix client and server versions together, I'm not a flutter user but it is essentially a server side environment, the client was working on flutter well before the browser version came along, this is why its barfing on 'import 'dart:html';', it would be the same in the VM.
I don't know anything about this new building for web targets that you can do(or is it will be able to do?) with flutter, you may be better asking the flutter guys.
Hi,
Thanks for the quick response.
I did find a way to resolve my issue. You might want to consider adding it to the library in a future version. To do it I had to create 4 tiny dart files. Here is the full contents of them:
The first is called MqttClientFactory.dart
export 'MqttClientFactoryNull.dart'
if (dart.library.html) 'MqttClientFactoryWeb.dart'
if (dart.library.io) 'MqttClientFactoryServer.dart';
The second is MqttClientFactoryWeb.dart
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_browser_client.dart';
MqttClient makeClient(String url, String clientId) => MqttBrowserClient(url, clientId);
The third is MqttClientFactoryServer.dart
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
MqttClient makeClient(String url, String clientId) {
var client = MqttServerClient(url, clientId);
client.useWebSocket = true;
return client;
}
And finally MqttClientFactoryNull.dart
import 'package:mqtt_client/mqtt_client.dart';
MqttClient makeClient(String url, String clientId) {
throw 'Platform not supported';
}
Once all of this was in place, all I had to do in my app was:
import 'package:mqtt_client/mqtt_client.dart';
import 'MqttClientFactory.dart';
...
_client = makeClient(url, clientId);
With this, it compiles and runs correctly on both browser and server with no code changes.
Thanks,
Don
Thanks for this, I've never been a fan of conditional library includes but this looks quite clean. I'll have a look at incorporating this into the client and maybe some of my other packages.
Hello I am looking to do the same thing. I cant get it to work with the code that you posted here. It would be cool to bring this up again and implement it into the package itself. I mean flutter is meant to use the same code to build for multiple platforms. It would make sense to add this in. THanks!
First, this is an amazing package. Thank you for your efforts.
I have a project that deploys to both browsers and mobile devices. It is amazing that the only difference required is the type of client I create.
In my dart code I do the following:
This works fine when building for web and the Dart Analyzer has no problem with it for either build. However when I try to build for mobile (android) I get the errors below. For now I just comment out the include version I don't need and it works fine. Can you suggest a better way to do this?
Thanks,
Don