Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to compile code conditional in Flutter?

I want to compile my Flutter code for web with a different dependency as for android. There is no dependency which supports both, so I need to find another way.

I found in the web the build.yaml but I dont understand it quite yet. Maybe this is the right option for me and somebody can help me understand it better (Thanks :D).

It should be on compile stage seperated because if I compile for web the android dependencys are blocking the compilation.

Skipping compiling pay_balance|lib/main_web_entrypoint.dart with ddc because some of its
transitive libraries have sdk dependencies that not supported on this platform:

firebase_core|lib/firebase_core.dart

https://github.com/dart-lang/build/blob/master/docs/faq.md#how-can-i-resolve-skipped-compiling-warnings

The endresult should be a Code which has different dependencys for web and android and not compile the other one. So when i develop for web the android dependencys should not be compiled!

like image 668
Maxi Avatar asked Sep 17 '19 11:09

Maxi


People also ask

How do you write if else in flutter?

Following is the syntax. if(boolean_expression){ // statement(s) will execute if the Boolean expression is true. } else { // statement(s) will execute if the Boolean expression is false. }


1 Answers

You have to use conditional imports as mentioned above. I did this recently and this is how:

You'll need a bit of verbose file creation but its not too bad. my_service.dart - used to do the import

my_service_main.dart - will be used to stub out the initial import because of the way Dart imports currently work

my_service_web.dart - will import Web specific libraries such as dart:html and do the web version of what you're trying to implement

my_service_mobile.dart - will import iOS/Android libraries such as dart:io and do the mobile version


  1. Create these 4 files
  2. Make sure your method is named the same thing in each
  3. throw UnsupportedError from the "main" version
  4. Handle imports

Putting it all together

// my_service_main.dart

void doTheThing() => throw UnsupportedError('doTheThing Unsupported')

// my_service_web.dart
import 'dart:html' as html;

void doTheThing(){
  // do your thing, use `html`, etc
}

//my_service_mobile.dart
import 'dart:io';

void doTheThing(){
  // do your thing using dart:io
}

// The export file
// my_service.dart

export 'my_service_main.dart'
  if (dart.library.js) 'my_service_web.dart'
  if (dart.library.io) 'my_service_mobile.dart'



// Then in your code you can import
import 'my_service.dart';

void main() {
  doTheThing();
}
like image 62
Jack Avatar answered Nov 12 '22 22:11

Jack