如何编写使用自定义应用程序的Flutter(Android)插件?

时间:2018-03-03 12:03:37

标签: android flutter stetho

我试图在these steps之后为stetho编写插件。

它需要在自定义应用程序的onCreate方法中进行一些初始化。

public class MyApplication extends Application {
  public void onCreate() {
    super.onCreate();
    Stetho.initializeWithDefaults(this);
  }
}

在AndroidManifest.xml中为同一个应用程序创建一个条目。

<manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        ...>
        <application
                android:name="MyApplication"
                ...>
         </application>
</manifest>      

但是在尝试使用依赖于此插件的flutter应用的flutter run时出现错误 -

D:\Dev\Repo\flutter_test\myapp\android\app\src\main\AndroidManifest.xml:16:9-57 Error:
        Attribute application@name value=(io.flutter.app.FlutterApplication) from AndroidManifest.xml:16:9-57
        is also present at [:stetho] AndroidManifest.xml:7:18-76 value=(com.vilokanlabs.stetho.stetho.MyApplication).
        Suggestion: add 'tools:replace="android:name"' to <application> element at AndroidManifest.xml:15:5-38:19 to override.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute application@name value=(io.flutter.app.FlutterApplication) from AndroidManifest.xml:16:9-57
        is also present at [:stetho] AndroidManifest.xml:7:18-76 value=(com.vilokanlabs.stetho.stetho.MyApplication).
        Suggestion: add 'tools:replace="android:name"' to <application> element at AndroidManifest.xml:15:5-38:19 to override.

2 个答案:

答案 0 :(得分:1)

将此行添加到您的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    **xmlns:tools="http://schemas.android.com/tools"**
    >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        **tools:replace="android:icon,android:theme,android:name"**
        >

答案 1 :(得分:0)

Android中似乎只允许一个应用程序节点。根据建议here并记录here

tool:replace也可能是@ sagar-chavada建议的解决方案,但它不起作用。不知何故,应用程序的清单被认为/解析晚于插件的清单,因此如果在应用程序的清单中使用工具:replace 有效(这是没有用的),但如果在插件的清单中使用则没有效果(&amp;) ;抛出错误。)

到目前为止,适用于我的唯一解决方案是插件中的extending the Flutter's application class -

public class MyApplication extends FlutterApplication {
    public void onCreate() {
        super.onCreate();
        Stetho.initializeWithDefaults(this);
    }

更新应用的清单文件以使用此新的子类 -

<!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->

    <application
        android:name="com.vilokanlabs.stetho.stetho.MyApplication"
        android:label="myapp"
        ...

事实证明,此处的评论表明相同。 对插件来说可能不是一个非常好的解决方案(一旦有两个竞争插件就会失败)但是它有效!