Create a view from native platform and retrieve it flutter channel

327 views Asked by At

I'm new to flutter but I read that there were no easy way in flutter to animate vector drawable as Android allowed to.

I own a vector progress bar which I want to animate to make the progress. Then I tried to use the platform channel to get the Android / iOS native code to animate my vector.

For now I only tested Android, and this is my code which is not working because of the view :

Flutter :

static const progressChannel = const MethodChannel("progress");
  Widget progressBar;

  Future<void> _getProgressBar() async {
    Widget progressBarView;
    try {
      var result = await progressChannel.invokeMapMethod('start');
      print("Result : ---- " + result.toString());
      progressBarView = result as Widget;
    }
    catch (e) {
      print("error channel : " + e.toString());
    }

    setState(() {
      progressBar = progressBarView;
    });
  }

Android :

class MainActivity: FlutterActivity() {

    private val CHANNEL = "progress"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "start") {
                val view = ImageView(this)
                result.success(startProgressBar(view))
            }
        }
    }

    private var vector: AnimatedVectorDrawableCompat? = null

    fun startProgressBar(view: ImageView): ImageView {
        val mainHandler = Handler(Looper.getMainLooper())
        vector = AnimatedVectorDrawableCompat.create(view.context, R.drawable.avd_progress_bar)
        view.setImageDrawable(vector)
        if (vector != null) {
            vector!!.registerAnimationCallback(object : androidx.vectordrawable.graphics.drawable.Animatable2Compat.AnimationCallback() {
                override fun onAnimationEnd(drawable: Drawable) {
                    super.onAnimationEnd(drawable)
                    mainHandler.post { vector!!.start() }
                }
            })
            vector!!.start()
        }
        return view
    }
}

Apparently I cannot create ImageView from Android code and retrieve it. Error :

E/MethodChannel#progress(32414): Failed to handle method call
E/MethodChannel#progress(32414): java.lang.IllegalArgumentException: Unsupported value: android.widget.ImageView{40dfc22 V.ED..... ......ID 0,0-0,0}

Is there a way to create a native View and retrieve it from Flutter ? Or another way to achieve this ?

0

There are 0 answers