githuseyingur / native_code_in_flutter_with_kotlin

See how Kotlin codes works in Flutter, doing tasks and showing results on the Flutter side.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

NATIVE CODE IN FLUTTER WITH KOTLIN

This repository is a demo about using Kotlin in Flutter to perform different operations and transfer the results to Flutter.

  • Reading a json file with countries and their capitals and displaying the read values as a list on the Flutter side. image Ekran görüntüsü 2024-03-09 174730
  • Accessing the phone's gallery, having the user select an image and showing this image on the Flutter side.
  • Accessing the phone's camera with permissions, having the user take a photo and showing this photo on the Flutter side.
static const platform = MethodChannel('my_channel');

Invoke Methods (main.dart)

String jsonString = await platform.invokeMethod('getJsonStringOfCapitals');
var base64Result = await platform.invokeMethod('selectImageInAlbum');
var base64Result = await platform.invokeMethod('takePhoto');

Native (MainActivity.kt)

Describing Request Codes For Opening Gallery & Camera

class MainActivity: FlutterActivity() {
  val CAMERA_REQUEST_CODE = 200
  val GALLERY_REQUEST_CODE = 300

Features

1) Reading a json file with countries and their capitals

  • reading the json file
if(call.method == "getJsonStringOfCapitals") {
  lateinit var jsonString: String
  try {
    jsonString = context.assets.open("country-by-capital-city.json").bufferedReader().use { it.readText()}
    result.success(jsonString)
  } catch (ex: Exception) {
    ex.printStackTrace()
  }  
}

We use result.success to access the result on the Flutter side.

2) Accessing the phone's gallery

  • open gallery
if(call.method == "selectImageInAlbum"){
  mResult = result
  val intent = Intent(Intent.ACTION_GET_CONTENT)
  intent.type = "image/*"

  if (intent.resolveActivity(packageManager) != null) {
  startActivityForResult(intent, GALLERY_REQUEST_CODE)
  }
}
  • onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  super.onActivityResult(requestCode, resultCode, data)
  if (resultCode == RESULT_OK) {

    if (requestCode == GALLERY_REQUEST_CODE) {
      var selectedImageUri = data?.getData()
      if (selectedImageUri != null) {
        val inputStream: InputStream = contentResolver.openInputStream(selectedImageUri)!!
        val bytes = ByteArray(inputStream.available())
        inputStream.read(bytes)
        inputStream.close()
        val base64Image = Base64.encodeToString(bytes, Base64.DEFAULT)
        mResult.success(base64Image)
      }
    }

3) Accessing the phone's camera with permissions

  • permission control
if(call.method == "takePhoto"){
  mResult = result
  if (ContextCompat.checkSelfPermission(applicationContext,android.Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
    openCamera()
  } else {
    ActivityCompat.requestPermissions(
      this, 
      arrayOf(android.Manifest.permission.CAMERA),
      CAMERA_REQUEST_CODE
    )
  }
}
  • the method that opens the camera
private fun openCamera() {
  val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
  startActivityForResult(intent, CAMERA_REQUEST_CODE)
}
  • permission result
 override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
  ) {
    when (requestCode) {
      CAMERA_REQUEST_CODE -> {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Kullanıcı kamera iznini verdi, kamera açma işlemine devam et
                openCamera()
            } else {
                // Kullanıcı kamera iznini reddetti, hata mesajı göster veya başka bir işlem yap
                mResult.error("PERMISSION_DENIED", "Kamera izni reddedildi.", null)
            }
        }
        // Diğer izin istek kodlarını işleyebilirsiniz (gerektiğinde)
    }
}
  • onActivityResult
// inside of  if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST_CODE ) {
  val photo: Bitmap = data?.extras?.get("data") as Bitmap
  val base64Image: String = convertBitmapToBase64(photo)
  mResult.success(base64Image)
}

About

See how Kotlin codes works in Flutter, doing tasks and showing results on the Flutter side.


Languages

Language:Dart 64.3%Language:Kotlin 25.6%Language:Swift 10.1%