Flutter原生数据交互插件flutternativedata的使用

发布于 1周前 作者 songsunli 来自 Flutter

Flutter原生数据交互插件 flutternativedata 的使用

Flutter Native Data 插件(简称 flutternativedata)是一个用于获取设备原生信息的强大工具。它支持多种方法如 getPackageInfo()getDeviceInfo()getMemoryInfo()getPlatformVersion(),能够帮助开发者轻松访问平台特定的数据,从而提升应用的用户体验。

支持情况

Android iOS
支持 SDK 16+ 12.0+

示例 Demo

Android 示例

Android 示例

iOS 示例

iOS 示例

使用示例

以下是一个完整的 Flutter 应用示例,展示了如何使用 flutternativedata 插件来获取和显示设备信息。

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutternativedata/entities/fn_device_info.dart';
import 'package:flutternativedata/entities/fn_memory_info.dart';
import 'package:flutternativedata/entities/fn_package_info.dart';
import 'package:flutternativedata/flutternativedata.dart';

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

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

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

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  late TabController tabController;
  String? platformVersion = 'Unknown';
  num? batteryLevel = 0;
  final _flutternativedataPlugin = Flutternativedata(showLogs: true);
  FNDeviceInfo? fnDeviceInfo;
  FNMemoryInfo? fnMemoryInfo;
  FNPackageInfo? fnPackageInfo;

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

  void initTabController() {
    tabController = TabController(length: 5, vsync: this);
  }

  // 异步初始化平台状态
  Future<void> initPlatformState() async {
    try {
      platformVersion = await _flutternativedataPlugin.getPlatformVersion() ?? 'Unknown platform version';
      batteryLevel = await _flutternativedataPlugin.getBatteryLevel() ?? 0;
      fnDeviceInfo = await _flutternativedataPlugin.getDeviceInfo();
      fnMemoryInfo = await _flutternativedataPlugin.getMemoryInfo();
      fnPackageInfo = await _flutternativedataPlugin.getPackageInfo();
    } on PlatformException catch (_) {
      platformVersion = 'Failed to get platform version.';
      batteryLevel = 0;
    }
    if (!mounted) return;

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(tabController.index == 0 ? "Device" : "Others"),
          bottom: TabBar(controller: tabController, tabs: [
            Tab(text: "Device", icon: Icon(Icons.home, color: Colors.indigo.shade500)),
            Tab(text: "Package Info", icon: Icon(Icons.person, color: Colors.indigo.shade500)),
            Tab(text: "Memory Info", icon: Icon(Icons.memory, color: Colors.indigo.shade500)),
            Tab(text: "Battery Level", icon: Icon(Icons.battery_0_bar_outlined, color: Colors.indigo.shade500)),
            Tab(text: "Platform Version", icon: Icon(Icons.place, color: Colors.indigo.shade500)),
          ]),
        ),
        body: TabBarView(controller: tabController, children: [
          SingleChildScrollView(
            child: Column(children: [
              const Text('DeviceInfo', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
              if (fnDeviceInfo != null)
                ...fnDeviceInfo!.toMap().entries.map((entry) => Text('${entry.key}: ${entry.value}\n')),
            ]),
          ),
          Column(children: [
            const Text('Package Info', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
            if (fnPackageInfo != null)
              ...fnPackageInfo!.toMap().entries.map((entry) => Text('${entry.key}: ${entry.value}\n')),
          ]),
          if (fnMemoryInfo != null)
            Column(children: [
              const Text('Memory Info', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
              ...fnMemoryInfo!.toMap().entries.map((entry) => Text('${entry.key}: ${entry.value}\n')),
            ]),
          if (batteryLevel != null)
            Column(children: [
              const Text('Battery Level', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
              Text(batteryLevel.toString()),
            ]),
          if (platformVersion != null)
            Column(children: [
              const Text('Platform Version', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
              Text(platformVersion.toString()),
            ]),
        ]),
      ),
    );
  }
}

使用说明

初始化插件

首先,需要在 initState 方法中初始化插件,并调用 initPlatformState 方法来获取设备信息。

final _flutternativedataPlugin = Flutternativedata(showLogs: true);

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

Future<void> initPlatformState() async {
  try {
    platformVersion = await _flutternativedataPlugin.getPlatformVersion() ?? 'Unknown platform version';
    batteryLevel = await _flutternativedataPlugin.getBatteryLevel() ?? 0;
    fnDeviceInfo = await _flutternativedataPlugin.getDeviceInfo();
    fnMemoryInfo = await _flutternativedataPlugin.getMemoryInfo();
    fnPackageInfo = await _flutternativedataPlugin.getPackageInfo();
  } on PlatformException catch (_) {
    platformVersion = 'Failed to get platform version.';
    batteryLevel = 0;
  }
  if (!mounted) return;

  setState(() {});
}

显示信息

通过 TabBarTabBarView 来组织不同的信息展示页面:

body: TabBarView(
  controller: tabController,
  children: [
    // Device Info
    SingleChildScrollView(
      child: Column(children: [
        const Text('DeviceInfo', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
        if (fnDeviceInfo != null)
          ...fnDeviceInfo!.toMap().entries.map((entry) => Text('${entry.key}: ${entry.value}\n')),
      ]),
    ),
    // Package Info
    Column(children: [
      const Text('Package Info', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
      if (fnPackageInfo != null)
        ...fnPackageInfo!.toMap().entries.map((entry) => Text('${entry.key}: ${entry.value}\n')),
    ]),
    // Memory Info
    if (fnMemoryInfo != null)
      Column(children: [
        const Text('Memory Info', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
        ...fnMemoryInfo!.toMap().entries.map((entry) => Text('${entry.key}: ${entry.value}\n')),
      ]),
    // Battery Level
    if (batteryLevel != null)
      Column(children: [
        const Text('Battery Level', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
        Text(batteryLevel.toString()),
      ]),
    // Platform Version
    if (platformVersion != null)
      Column(children: [
        const Text('Platform Version', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
        Text(platformVersion.toString()),
      ]),
  ],
),

这样,你就可以在一个简单的 Flutter 应用中集成并使用 flutternativedata 插件来获取和显示设备的各种信息了。希望这个示例对你有所帮助!


更多关于Flutter原生数据交互插件flutternativedata的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter原生数据交互插件flutternativedata的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter应用中使用flutternativedata插件进行原生数据交互的代码案例。请注意,由于flutternativedata不是一个广泛认知的标准Flutter插件,我将假设你指的是一个自定义的或假想的插件,用于展示原生平台(Android和iOS)与Flutter之间的数据交互。如果这是一个实际存在的插件,请参考其官方文档进行调整。

Flutter 端代码

首先,确保你的pubspec.yaml文件中已经添加了flutternativedata插件(假设它已经存在于pub.dev或者是一个本地插件):

dependencies:
  flutter:
    sdk: flutter
  flutternativedata:
    path: ./path/to/your/local/plugin  # 如果是本地插件
    # 或者
    # version: ^x.y.z  # 如果是pub.dev上的插件

然后,在Flutter代码中导入并使用该插件:

import 'package:flutter/material.dart';
import 'package:flutternativedata/flutternativedata.dart';  // 假设插件的导入路径

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _nativeData = "Loading...";

  @override
  void initState() {
    super.initState();
    // 调用原生方法获取数据
    FlutterNativeData.getDataFromNative().then((data) {
      setState(() {
        _nativeData = data;
      });
    }).catchError((error) {
      print("Error fetching data from native: $error");
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Native Data Interaction'),
        ),
        body: Center(
          child: Text('Native Data: $_nativeData'),
        ),
      ),
    );
  }
}

原生端代码(Android)

在Android原生代码中,你需要创建一个MethodChannel来与Flutter进行通信。假设你已经有一个Flutter插件项目结构,以下是在MainActivity.kt(或MainActivity.java)中的代码示例:

package com.example.flutternativedata

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.example.flutternativedata/channel"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "getDataFromNative") {
                // 这里返回你想要传递给Flutter的数据
                val nativeData = "Hello from Native Android!"
                result.success(nativeData)
            } else {
                result.notImplemented()
            }
        }
    }
}

原生端代码(iOS)

在iOS原生代码中,同样需要创建一个FlutterMethodChannel来与Flutter进行通信。在你的AppDelegate.swift(或AppDelegate.m)中添加以下代码:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let channel = FlutterMethodChannel(name: "com.example.flutternativedata/channel", binaryMessenger: controller.binaryMessenger)
    channel.setMethodCallHandler({
      (call: FlutterMethodCall, result: @escaping FlutterResult) in
      if call.method == "getDataFromNative" {
        let nativeData = "Hello from Native iOS!"
        result(nativeData)
      } else {
        result(FlutterMethodNotImplemented)
      }
    })
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

以上代码展示了如何在Flutter应用中通过flutternativedata插件(假设存在)与原生平台进行数据交互。请根据你的实际情况调整代码,特别是插件的导入路径和MethodChannel的名称。如果flutternativedata是一个实际存在的插件,请参考其官方文档获取更准确的实现细节。

回到顶部