Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import third party android library to java file in flutter

I am looking to import a java library to a flutter application. I understand that I will need to call the methods of this java file through a dart bridge or platform channel per https://flutter.io/platform-channels/. However I have yet to be able to make the methods from the library Im trying to import callable or importable. The methods are available when looking at the java file alone in android studio but when viewed with flutter they are unavailable.

like image 210
Tkgn15 Avatar asked Jul 26 '18 17:07

Tkgn15


People also ask

Can we use Java library in Flutter?

Yes you can. It is helpful if you are using SDK that gives you native code for both Android and iOS, otherwise it will be difficult. Good luck! Save this answer.

How do I add a library to Flutter?

You can go to the pubspec. yaml file and add dependencies ,under dependencies and then packages get will do the work. or you can run flutter pub get in the terminal.

How do I import a jar file into Flutter?

Right-click on it, go to -> Flutter -> Open project in android studio. Go to File->Project Strucuture-> Dependencies. Select the name of plugin (you should ad dependency here, not in app or All Modules) Click on the "+" button to add a new dependency.

How do I add Java code to Flutter?

To use Java or Objective-C, use the -i and/or -a flags: In a terminal run: flutter create -i objc -a java batterylevel.


1 Answers

With the extra info given, I was able to reproduce the issue.

To edit the native Android app, you have to open it in a new instance of Android Studio:

enter image description here

To add the the libraryx io.particle:cloudsdk:0.5.0, you have to add it to the build.gradle in the app subfolder. You also have to enable Java 1.8 support:

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

...

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'io.particle:cloudsdk:0.5.0'
}

The IDE will only recognize the library when you open the Android project in a separate window. The Flutter app will still compile without a problem.

To get rid of the red error underlining in your Flutter project, you can unload, then reload the Android module (right click on android folder > Load/Unload modules...):

enter image description here

like image 101
boformer Avatar answered Nov 14 '22 20:11

boformer