flutter create --template=plugin wechat
上面的代码中,表示以 plugin
模板创建一个名为 wechat
的 package
,创建完成之后,整个项目的目录结构就都提供好了,并且官方还提供了一些基本开发示例。
目录结构
- android // Android 相关原生代码目录
- ios // ios 相关原生代码目录
- lib // Dart 代码目录
- example // 一个完整的调用了我们正在开发的插件的 Flutter App
- pubspec.yaml // 项目配置文件
从 example/lib/main.dart 开始
在开发我们的应用之后,先来了解一下 flutter 为我们生成的文件们,打开 example/lib/main.dart,代码如下
import ‘package:flutter/material.dart’;
import ‘dart:async’;
import ‘package:flutter/services.dart’;
import ‘package:wechat/wechat.dart’;
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
String _platformVersion = ‘Unknown’;
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await Wechat.platformVersion;
} on PlatformException {
platformVersion = ‘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 = platformVersion;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text(‘Plugin example app’),
),
body: Center(
child: Text(‘Running on: $_platformVersion\n’),
),
),
);
}
}
这里需要特别注意的就是 initPlatformState() 方法中对 Wechat.platformVersion 的调用,这里面的 Wechat 就是我们的插件,platformVersion 就是插件提供的 get 方法,跟着这个文件,找到 lib/wechat.dart 文件,代码如下:
import ‘dart:async’;
import ‘package:flutter/services.dart’;
class Wechat {
static const MethodChannel _channel =
const MethodChannel(‘wechat’);
static Future get platformVersion async {
final String version = await _channel.invoke