I need to develop a cross platform app using flutter that supports mobile as well as web platforms. I need an image picker that works for mobile as well as web. Currently I am using image picker flutter plugin for mobile and flutter_web_image_picker for web. But the build fails as flutter_web_image_picker uses dart:HTML and it is not supported for mobile builds. I need to know that how shall I conditionally render web pickers for their respective platforms as having two separate code bases won't make any sense?
-
Could you please show your code that you have tried – Ronak Patel Sep 08 '20 at 11:20
2 Answers
Might be very late, but this is how we can execute any code conditionally for different platforms in flutter.
import 'package:flutter/foundation.dart' show kIsWeb;
Then in the function code -
if(kIsWeb){
... web specific code
} else {
... mobile specific code
}

- 79
- 11
So it seems like you can do conditional importing based on some flutter environment variables and a couple of properly named classes. The example uses an abstract class to give a stub implementation to both the web and the mobile platform implementations. Reference links:
- How to import platform specific dependency in Flutter/Dart? (Combine Web with Android/iOS)
- https://gpalma.pt/blog/conditional-importing/
import 'src/hw_none.dart' // Stub implementation
if (dart.library.io) 'src/hw_io.dart' // dart:io implementation - you can import dart:io in this file.
if (dart.library.html) 'src/hw_html.dart'; // dart:html implementation - you can import dart:html in this file
This will do is check to see which environment you are executing on by checking to see if dart.library.io or dart.library.html environment variable is set.
dart:html is only available when dart.library.html is defined. This is the library that the web file picker uses.
dart:io is only available for import when dart.library.io is defined. This is what is needed for the mobile file pickers.

- 23
- 5