Issue
I want to know what should be the best way to have a platform specific function on a federated plugin and how to call it from the main app.
Lets see, for example, this federated plugin code:
- Platform interface where a function is defined:
abstract class FlutterGetPlatformStringPlatform extends PlatformInterface {
...
Future<String> getPlatformString() {
throw UnimplementedError();
}
...
}
- Android implementation:
abstract class AndroidGetPlatformString extends FlutterGetPlatformStringPlatform {
...
@override
Future<String> getPlatformString() {
// Some native method
}
...
}
- Web implementation:
abstract class WebGetPlatformString extends FlutterGetPlatformStringPlatform {
...
@override
Future<String> getPlatformString() {
// Some native method
}
String specificNativeVariable = SpecificNativeVariable();
void specificNativeFunction() {
// More stuff
}
...
}
So the question here is on my app I import the plugin on my pubspec.yaml
and then on the code import 'package:flutter_platform_string_interface/flutter_platform_string_interface.dart';
. So, how I have to call the web only specificNativeFunction
or how can I set the web only SpecificNativeVariable
?
Should I import the flutter_platform_string_web
, or how I have to instantiate the platform interface?
Solution
There are several ways you could do this:
- As you’ve shown, with the plugin client importing
flutter_platform_string_web
. - Use the pattern demonstrated in the
in_app_purchase
plugin, with the plugin client importingflutter_platform_string_web
. This has the advantage that the client doesn’t need to import the entire platform implementation, and is therefore much less likely to think the should call other platform implementation methods directly (which is almost always a bad idea). - Make the method part of the app-facing package and document that it’s only implemented on web. That’s how platform-specific methods worked prior to the creation of federated plugins, but it’s not really an encouraged practice now. It doesn’t scale well as you add more platforms with their own specific methods, doesn’t allow for using types that are platform-specific, etc.
Answered By – smorgan
Answer Checked By – Timothy Miller (FlutterFixes Admin)