Is there a downside to not making MethodChannels static const in Flutter?
377
The MethodChannel
instance where it is defined is const
by convention, and to be honest there is little reason for it ever not to be. However, while the typical implementation has the channel defined in the service class, it doesn't have to be. You could also easily define it elsewhere and then pass it to your service class via dependency injection.
DI Init File
const platform = MethodChannel(...);
void initDI() {
GetIt.I.registerSingleton(platform, "MyMethodChannel");
}
Service File
class PlatformService {
final MethodChannel platform;
PlatformService()
: platform = GetIt().I.get("MyMethodChannel");
...
}
Comments
-
Paco1 over 1 year
The examples in the Flutter docs have the MethodChannel they are using (to communicate with the native host) declared as
static const
, directly in the Widget that's using it. To bring some separation into it, I'm trying to lay out my app so that the MethodChannel- resides in the BLoCs or even the underlying service layer instead of directly in the Widget, and
- is instead injected, to make everything easily unit-testable.
Is it a problem (performance-related, bug-inducing, etc.) if the MethodChannel is not
static
andconst
?-
Abion47 over 4 yearsI'm not sure if there's a practical downside to having multiple instances of a
MethodChannel
that have the same channel name, but I'm also struggling to see the upside. Each of those instances are going to point to the same platform channel, so there's no reason not to have it bestatic const
, and doing so creates a canonical instance that the program can reuse. You can still use dependency injection even if you declare itstatic const
, so why wouldn't you? -
Paco1 about 4 yearsUnfortunately at least with get_it it's not possible, as far as I know: "Const variables must be initialized with a constant value." It can still be static, just not const. Even if having a static const dependency would lead my main driver for using dependency injection (which is unit testing) ad absurdum anyway, please write up an answer if it is possible and I just don't get it. I'll change my question slightly and accept your answer.
-
Abion47 about 4 yearsI still don't understand your use case. There's nothing preventing you from setting up a singleton or a factory in get_it that returns a constant variable.
-
Paco1 about 4 yearsOk, my concrete problem is: my service class needs access to a MethodChannel. My app doesn't only have one channel, so I need to resort to named injection. Now of course I can declare
const MethodChannel(...)
in get_it, but even thenconst MethodChannel platform = sl.get("MyMethodChannel");
gives me the error "Const variables must be initialized with a constant value." -
Abion47 about 4 yearsThe
MethodChannel
instance where its originally defined should be constant, but there's no rule stating the reference in your service class has to be.