Flutter: Conditional Import for Web and Native

The Rivepod way to provide platform specific implementations of a midi player

Alfred Schilken
5 min readJan 2, 2021

--

This article shows you how to use different implementations for web and for native. This is tricky when the web implementation needs to import a library which is not available for native platforms. A little example uses this trick to play midi on web and on native plaforms.

I’m working on an iOS app that will play midi sounds to learn the notes on a guitar. Most of the development I do on a really old MacBook Pro (2011) which can’t build iOS Apps any more. So I build my App for Web and this works fine. Only for deployment on my iPhone I use a newer Mac.

Playing midi on web is quite different from playing it on iOS. Happily there is the package flutter_midi by Rody Davis which has a little example for both web and native. The problem with these example is, that I needed to comment out the import of web_midi.dart in my midi.dart file every time I wanted to build the native version. That’s because this file imports dart:js and javascript isn’t supported on the native platforms. On the web platform dart:js provides the bridge between the flutter code and the javascript code which is loaded and callable in index.html. You get the follwing error if you import a javascript library in a native…

--

--

Alfred Schilken

Software Developer for more than 35 years, started with C and C++, after Java, Python, Groovy, Lua, Golang and Swift now focussing on Dart and Flutter