Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Activity and Context in Flutter plugin

Tags:

flutter

dart

One of my package need to access Context and I got it from onAttachedToEngine -> flutterPluginBinding.getApplicationContext() to a variable but this crash the app with NullPointerException. The reason is I think I am trying to use the Context before it is assigning to the variable.

What is the correct way to access the Context?

And how can I get the Activity if I wanted too?

like image 295
Blasanka Avatar asked Feb 03 '20 23:02

Blasanka


People also ask

How do you get activity on Flutter plugin?

Show activity on this post. activity = binding. activity; should be activity = binding. getActivity(); Else code works great for me!

How do you get context in FlutterActivity?

1 Answer. Show activity on this post. Create SharedPreferencesHandler. java file and add code below!

What is FlutterActivity in Flutter?

FlutterActivity supports the display of an Android "launch screen" as well as a Flutter-specific "splash screen". The launch screen is displayed while the Android application loads. It is only applicable if FlutterActivity is the first Activity displayed upon loading the app.

How do I add plugins to Flutter?

To create a plugin package, Use the --template=plugin flag with the Flutter create command. Use the --platforms= option followed by a comma-separated list to specify the plugin supports platforms. Available platforms are Android, iOS, web, Linux, macOS, and Windows.


1 Answers

Depends on flutter document in Create-Flutter-Plugin, Follow these steps:

1- Import ActivityAware:

import io.flutter.embedding.engine.plugins.activity.ActivityAware

2- implement ActivityAware in your class:

public class ClassName: FlutterPlugin, MethodCallHandler, ActivityAware { 

3- Define lateinit variables to use it class:

private lateinit var context: Context
private lateinit var activity: Activity

4- Add these functions:

override fun onDetachedFromActivity() {
    TODO("Not yet implemented")
}

override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    TODO("Not yet implemented")
}

override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activity = binding.activity;
}

override fun onDetachedFromActivityForConfigChanges() {
    TODO("Not yet implemented")
}

5- Add this line in onAttachedToEngine function:

context = flutterPluginBinding.applicationContext

You can see this full code for more understanding:

package com.example.flutter_plugin_name

import android.app.Activity
import android.content.Context
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar


public class FlutterPluginName: FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel

    private lateinit var context: Context
    private lateinit var activity: Activity

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutter_plugin_name")
    channel.setMethodCallHandler(this);
    context = flutterPluginBinding.applicationContext
  }



  // This static function is optional and equivalent to onAttachedToEngine. It supports the old
  // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
  // plugin registration via this function while apps migrate to use the new Android APIs
  // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
  //
  // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
  // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
  // depending on the user's project. onAttachedToEngine or registerWith must both be defined
  // in the same class.
  companion object {
    @JvmStatic
    fun registerWith(registrar: Registrar) {
      val channel = MethodChannel(registrar.messenger(), "flutter_plugin_name")
      channel.setMethodCallHandler(FlutterMapboxTurnByTurnPlugin())
    }
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    }

    else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

    override fun onDetachedFromActivity() {
        TODO("Not yet implemented")
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        TODO("Not yet implemented")
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity;
    }

    override fun onDetachedFromActivityForConfigChanges() {
        TODO("Not yet implemented")
    }
}
like image 175
AnasSafi Avatar answered Oct 13 '22 00:10

AnasSafi