new_battery_plugin 0.0.1 copy "new_battery_plugin: ^0.0.1" to clipboard
new_battery_plugin: ^0.0.1 copied to clipboard

A Flutter plugin to get battery level and platform version.

example/lib/main.dart

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _batteryLevel = 'Unknown';
  String _platformVersion = 'Unknown';
  final _newBatteryPlugin = NewBatteryPlugin();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String batteryLevel;
    String platformVersion;

    // Retrieve the battery level and platform version.
    try {
      final version = await _newBatteryPlugin.getPlatformVersion();
      platformVersion = version ?? 'Failed to get platform version.';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }


    try {
      final level = await _newBatteryPlugin.getBatteryLevel();
      batteryLevel = level != null ? '$level%' : 'Failed to get battery level.';
    } on PlatformException {
      batteryLevel = 'Failed to get battery level.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _batteryLevel = batteryLevel;
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Battery Level Plugin Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Battery level: $_batteryLevel'),
              Text('Platform version: $_platformVersion'),
            ],
          ),
        ),
      ),
    );
  }
}
1
likes
150
points
0
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin to get battery level and platform version.

Homepage

Documentation

API reference

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on new_battery_plugin

Packages that implement new_battery_plugin