Flutter基础模板插件baseflow_plugin_template的使用

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

Flutter基础模板插件baseflow_plugin_template的使用

baseflow_plugin_template 是一个用于创建Flutter插件示例的模板。本文将介绍如何使用该插件,并提供一个完整的示例代码。

开始使用

添加依赖

首先,在你的 pubspec.yaml 文件中添加 baseflow_plugin_template 的依赖:

dependencies:
  baseflow_plugin_template: ^2.2.0

运行模板应用

接下来,你可以使用 BaseflowPluginExample 类来运行模板应用。以下是一个完整的示例代码:

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

void main() {
  runApp(BaseflowPluginExample(
    pluginName: 'test plugin',
    githubURL: 'https://github.com/baseflow/baseflow_plugin_template',
    pubDevURL: 'https://pub.dev/publishers/baseflow.com/packages',
    pages: [CenteredText.createPage()],
  ));
}

class CenteredText extends StatelessWidget {
  static ExamplePage createPage() {
    return ExamplePage(Icons.text_fields, (context) => const CenteredText());
  }

  const CenteredText({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text('Very simple example'),
    );
  }
}

代码解释

  1. 导入包

    import 'package:baseflow_plugin_template/baseflow_plugin_template.dart';
    import 'package:flutter/material.dart';
    
  2. 主函数

    void main() {
      runApp(BaseflowPluginExample(
        pluginName: 'test plugin',
        githubURL: 'https://github.com/baseflow/baseflow_plugin_template',
        pubDevURL: 'https://pub.dev/publishers/baseflow.com/packages',
        pages: [CenteredText.createPage()],
      ));
    }
    
    • pluginName: 插件的名称。
    • githubURL: 插件的GitHub仓库地址。
    • pubDevURL: 插件在Pub Dev上的发布地址。
    • pages: 一个包含示例页面的列表。
  3. 示例页面

    class CenteredText extends StatelessWidget {
      static ExamplePage createPage() {
        return ExamplePage(Icons.text_fields, (context) => const CenteredText());
      }
    
      const CenteredText({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const Center(
          child: Text('Very simple example'),
        );
      }
    }
    
    • createPage 方法返回一个 ExamplePage 对象,该对象包含一个图标和一个构建页面的函数。
    • CenteredText 是一个简单的示例页面,显示居中的文本。

通过以上步骤,你就可以成功地使用 baseflow_plugin_template 插件并运行一个简单的示例应用。希望这对你的开发工作有所帮助!


更多关于Flutter基础模板插件baseflow_plugin_template的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter基础模板插件baseflow_plugin_template的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用baseflow_plugin_template来创建一个基础插件的示例代码。这个模板由Baseflow提供,旨在简化创建Flutter插件的流程。

1. 设置Flutter项目

首先,确保你已经安装了Flutter SDK,并创建了一个新的Flutter项目:

flutter create my_flutter_app
cd my_flutter_app

2. 添加baseflow_plugin_template

接下来,你需要将baseflow_plugin_template作为模板添加到你的项目中。不过,值得注意的是,baseflow_plugin_template并不是一个可以直接添加到pubspec.yaml的公开包,而是一个用于生成插件骨架的工具。因此,你需要手动下载或使用它生成的代码结构。

为了演示,我们假设你已经有了这个模板的代码结构,或者你将使用Baseflow提供的工具生成它。

3. 插件结构

假设你已经有了一个基于baseflow_plugin_template生成的插件目录结构,如下所示:

my_flutter_app/
├── android/
├── ios/
├── lib/
│   └── my_custom_plugin.dart
├── my_custom_plugin/
│   ├── android/
│   │   ├── build.gradle
│   │   └── src/
│   │       └── main/
│   │           └── java/
│   │               └── com/
│   │                   └── example/
│   │                       └── my_custom_plugin/
│   │                           ├── MyCustomPlugin.java
│   │                           └── MyCustomPlugin.kt (optional)
│   ├── ios/
│   │   └── Classes/
│   │       └── MyCustomPlugin.swift
│   ├── pubspec.yaml
│   └── CHANGELOG.md
├── pubspec.yaml
└── ...

4. 配置插件的pubspec.yaml

my_custom_plugin/pubspec.yaml中,你需要配置插件的基本信息:

name: my_custom_plugin
description: A new flutter plugin project.
version: 0.0.1
author: Your Name <your.email@example.com>
homepage: https://github.com/yourusername/my_custom_plugin

environment:
  sdk: ">=2.12.0 <3.0.0"
  flutter: ">=1.17.0"

dependencies:
  flutter:
    sdk: flutter

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  plugin:
    platforms:
      android:
        package: com.example.my_custom_plugin
        pluginClass: MyCustomPlugin
      ios:
        pluginClass: MyCustomPlugin

5. 实现插件功能

Android

MyCustomPlugin.java中,实现你的插件逻辑:

package com.example.my_custom_plugin;

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.BinaryMessenger;
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 android.app.Activity;

public class MyCustomPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
  private MethodChannel channel;
  private Activity activity;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    BinaryMessenger messenger = flutterPluginBinding.getBinaryMessenger();
    channel = new MethodChannel(messenger, "my_custom_plugin");
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      String version = android.os.Build.VERSION.RELEASE;
      result.success(version);
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

  @Override
  public void onAttachedToActivity(ActivityPluginBinding binding) {
    activity = binding.getActivity();
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {
    activity = null;
  }

  @Override
  public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
    activity = binding.getActivity();
  }

  @Override
  public void onDetachedFromActivity() {
    activity = null;
  }
}

iOS

MyCustomPlugin.swift中,实现你的插件逻辑:

import Flutter

public class MyCustomPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "my_custom_plugin", binaryMessenger: registrar.messenger())
    let instance = MyCustomPlugin()
    _ = channel.setMethodCallHandler(onMethodCall: instance.handle(_:result:))
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    if call.method == "getPlatformVersion" {
      let version = UIDevice.current.systemVersion
      result(version)
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}

6. 使用插件

最后,在你的Flutter应用中使用这个插件。在lib/my_flutter_app.dart中:

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

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

class MyApp extends StatelessWidget {
  static const platform = MethodChannel('my_custom_plugin');

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Running on: '),
              Text('$_platformVersion\n'),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _getPlatformVersion,
          tooltip: 'Get Platform Version',
          child: Icon(Icons.phone_android),
        ),
      ),
    );
  }

  String _platformVersion = 'Unknown';

  Future<void> _getPlatformVersion() async {
    String version;
    // Platform messages may fail, so we use a try-catch block.
    try {
      version = await MyCustomPlugin.platformVersion;
    } on PlatformException {
      version = 'Failed to get platform version.';
    }

    // 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(() {
      _platformVersion = version;
    });
  }
}

别忘了在lib/my_custom_plugin.dart中定义MyCustomPlugin类及其静态方法:

import 'dart:async';

import 'package:flutter/services.dart';

class MyCustomPlugin {
  static const MethodChannel _channel = const MethodChannel('my_custom_plugin');

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }
}

总结

以上是如何基于baseflow_plugin_template创建一个简单的Flutter插件的示例代码。请注意,实际项目中可能需要更多的配置和错误处理。希望这个示例能帮助你理解如何使用这个模板来创建自己的Flutter插件。

回到顶部