'Flutter method channel error. { Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel battery) }

so i followed everthing from 'https://flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-java-tab' but when I click the floating button in my device this error is shown.

[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel battery)

E/flutter ( 4580): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:159:7)
E/flutter ( 4580): <asynchronous suspension>
E/flutter ( 4580): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
E/flutter ( 4580): #2      _batteryState._getBatteryLevel (package:flutter_app/main.dart:45:37)
E/flutter ( 4580): #3      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter ( 4580): #4      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter ( 4580): #5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter ( 4580): #6      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter ( 4580): #7      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter ( 4580): #8      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
E/flutter ( 4580): #9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
E/flutter ( 4580): #10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
E/flutter ( 4580): #11     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
E/flutter ( 4580): #12     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 4580): #13     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
E/flutter ( 4580): #14     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
E/flutter ( 4580): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
E/flutter ( 4580): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter ( 4580): #17     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter ( 4580): #18     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter ( 4580): #19     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter ( 4580): #20     _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 4580): #21     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 4580): #22     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 4580): #23     _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 4580): #24     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter ( 4580): 

Main.dart:-

import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main(){
  runApp(
      MaterialApp(
        home: battery()



    )
  );
}

class battery extends StatefulWidget {

  @override
  _batteryState createState() => _batteryState();
}

class _batteryState extends State<battery> {
  static const platform = const MethodChannel('battery');
  String _batteryLevel = 'error';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BatteryDetails'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            FloatingActionButton.extended(onPressed: _getBatteryLevel, label: Text('Get battery info')),
            Text(_batteryLevel),
          ],
        )        
      )
    );
  }
  Future<void> _getBatteryLevel() async{
  String BatteryLevel;
  try {
  final int result = await platform.invokeMethod('getBatteryLevel');
  BatteryLevel = 'battery Level is $result %.';
  }on PlatformException catch (e){
  BatteryLevel = "failed to get battery level: '&{e.message}'";
  }
  setState(() {
    _batteryLevel = BatteryLevel;
  });
  }
}

MainActivity.java:-

package com.example.flutter_app;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "battery";

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) -> {
                            // Note: this method is invoked on the main thread.
                            if (call.method.equals("getBatteryLevel")) {
                                int batteryLevel = getBatteryLevel();

                                if (batteryLevel != -1) {
                                    result.success(batteryLevel);
                                } else {
                                    result.error("UNAVAILABLE", "Battery level not available.", null);
                                }
                            } else {
                                result.notImplemented();
                            }
                        }
                );
    }
    private int getBatteryLevel() {
        int batteryLevel = -1;
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
            batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = new ContextWrapper(getApplicationContext()).
                    registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
                    intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        }

        return batteryLevel;
    }
}

i am new to flutter, can you help me also can anyone explain me what is happening in

public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) 

this part of code. thank you.



Solution 1:[1]

Based from the the error you got, you're getting a MissingPluginException from the method getBatteryLevel. This means the app is unable to find the method you're trying to call.

If you just tried running the app using hot reload, changes on platform-specific code might have not registered. Running the app using restart should usually solve the issue. If you're still having issues, you can print the log of the call.method being passed to the MethodChannel in your MainActivity.java to see if the method name from Flutter is being received as expected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Omatt