{1}–第1章课程介绍与学习指南
{2}–第2章Flutter整体介绍
2-1Flutter技术发展概览
2-2Flutter技术发展概览
2-3Flutter技术发展概览
2-4Flutter的整体框架结构介绍
2-5为什么选择Dart语言
2-6Dart语言特性
2-7Dart的线程管理及框架
2-8Dart的异步编程
await修饰的代码会等待,async修饰的代码会直接执行不阻塞
微任务队列尽量不用,让它去进行内核工作,我们的任务放到事件队列
2-9工程结构
2-10布局方式及差异
2-11Flutter技术发展概览
{3}–第3章开发工具安装及环境搭建
{4}–第4章Flutter实现混合式开发
4-1Flutter混合开发 本章导学
4-2混合开发技术简介
4-3混合开发项目管理方式
4-4Flutter工程模式
4-5Flutter工程创建及项目运行
4-6BasicMessageChannel基础消息通道(一)
// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String? _message;
static const _channel = BasicMessageChannel("msgChan", StringCodec());
void initState() {
super.initState();
// 通过BasicMessageChannel注册一个接收回调,并返回消息
_channel.setMessageHandler((message) async {
print('receive message: $message');
setState(() {
_message = message;
});
return 'ACK from dart';
});
}
Future<void> _sendMessage() async {
String? msg = await _channel.send('Hello from dart');
print('Send msg: $msg');
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$_message',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
4-7BasicMessageChannel基础消息通道(二)
package com.example.mc
import android.os.Handler
import android.os.Looper
import android.util.Log
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.StringCodec
import java.util.logging.Logger
class MainActivity : FlutterActivity() {
private val TAG = "MainActivity"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// 初始化BasicMessageChannel传入名称,要和dart里定义的名称一致
val channel = BasicMessageChannel(
flutterEngine.dartExecutor.binaryMessenger, "msgChan", StringCodec.INSTANCE
);
// 接收回调,返回ACK
// 最后一个方法直接省略
channel.setMessageHandler { message, reply ->
Log.d(TAG, "configureFlutterEngine: Android receive message: " + message)
reply.reply("ACK from Android")
// 延迟1秒发送
Handler(Looper.getMainLooper()).postDelayed({
// 发送消息给dart
channel.send("hello from android")
}, 1000)
}
}
}
4-8EventChannel事件通道
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String? _message;
// 1.创建channel
// static const _channel = BasicMessageChannel("msgChan", StringCodec());
static const _channel = EventChannel("eventChan");
void initState() {
super.initState();
// 2.通过channel实例注册
// 通过BasicMessageChannel注册一个接收回调,并返回消息
// _channel.setMessageHandler((message) async {
// print('receive message: $message');
// setState(() {
// _message = message;
// });
// return 'ACK from dart';
// });
_channel.receiveBroadcastStream().listen((event) {
print('receive event: $event');
setState(() {
_message = event;
});
}, onError: (error) {
print('receive error: $error');
}, cancelOnError: true); // err时取消监听
}
// Future<void> _sendMessage() async {
// String? msg = await _channel.send('Hello from dart');
// print('Send msg: $msg');
// }
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'wait for message',
),
Text(
'$_message',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
// onPressed: _sendMessage,
onPressed: () {},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
package com.example.mc
import android.os.Handler
import android.os.Looper
import android.util.Log
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
class MainActivity : FlutterActivity() {
private val TAG = "MainActivity"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// 初始化BasicMessageChannel传入名称,要和dart里定义的名称一致
// val channel = BasicMessageChannel(
// flutterEngine.dartExecutor.binaryMessenger, "msgChan", StringCodec.INSTANCE
// );
val channel = EventChannel(
flutterEngine.dartExecutor.binaryMessenger, "eventChan"
)
// 接收回调,返回ACK
// kt语法糖: 最后一个方法直接省略
// channel.setMessageHandler { message, reply ->
// Log.d(TAG, "configureFlutterEngine: Android receive message: " + message)
// reply.reply("ACK from Android")
//
// // 延迟1秒发送
// Handler(Looper.getMainLooper()).postDelayed({
// // 发送消息给dart
// channel.send("hello from android")
// }, 1000)
// }
// 设置事件流的handler
channel.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
Log.d(TAG, "onListen: eventChan")
Handler(Looper.getMainLooper()).postDelayed({
Log.d(TAG, "onListen: send ADK from android")
events?.success("ACK from android")
}, 1000)
}
override fun onCancel(arguments: Any?) {
Log.d(TAG, "onCancel: eventChan cancel")
}
})
}
}
4-9混合开发的关键MethodChannel方法通道(一)
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
// ...
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String? _message;
// 1.创建channel
// static const _channel = BasicMessageChannel("msgChan", StringCodec());
// static const _channel = EventChannel("eventChan");
static const _channel = MethodChannel('methodChan');
void initState() {
super.initState();
getFlutterInfo();
// 2.通过channel实例注册
// 通过BasicMessageChannel注册一个接收回调,并返回消息
// _channel.setMessageHandler((message) async {
// print('receive message: $message');
// setState(() {
// _message = message;
// });
// return 'ACK from dart';
// });
// _channel.receiveBroadcastStream().listen((event) {
// print('receive event: $event');
// setState(() {
// _message = event;
// });
// }, onError: (error) {
// print('receive error: $error');
// }, cancelOnError: true); // err时取消监听
}
// Future<void> _sendMessage() async {
// String? msg = await _channel.send('Hello from dart');
// print('Send msg: $msg');
// }
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme
.of(context)
.colorScheme
.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'wait for message',
),
Text(
'$_message',
style: Theme
.of(context)
.textTheme
.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
// onPressed: _sendMessage,
onPressed: () {},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
Future<void> getFlutterInfo () async {
final Map<String, dynamic> map = {
'name': 'flutter',
'version': "3",
'language': 'dart',
'android_api': 32
};
String res = await _channel.invokeMethod('getFlutterInfo', map);
print('method invoke res: $res');
}
}
package com.example.mc
import android.util.Log
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
companion object {
val METHOD_NAME = "getFlutterInfo"
}
private val TAG = "MainActivity"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// 初始化BasicMessageChannel传入名称,要和dart里定义的名称一致
// val channel = BasicMessageChannel(
// flutterEngine.dartExecutor.binaryMessenger, "msgChan", StringCodec.INSTANCE
// );
// val channel = EventChannel(
// flutterEngine.dartExecutor.binaryMessenger, "eventChan"
// )
val channel = MethodChannel(
flutterEngine.dartExecutor.binaryMessenger, "methodChan"
)
// 接收回调,返回ACK
// kt语法糖: 最后一个方法直接省略
// channel.setMessageHandler { message, reply ->
// Log.d(TAG, "configureFlutterEngine: Android receive message: " + message)
// reply.reply("ACK from Android")
//
// // 延迟1秒发送
// Handler(Looper.getMainLooper()).postDelayed({
// // 发送消息给dart
// channel.send("hello from android")
// }, 1000)
// }
// 设置事件流的handler
// channel.setStreamHandler(object : EventChannel.StreamHandler {
// override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
// Log.d(TAG, "onListen: eventChan")
//
// Handler(Looper.getMainLooper()).postDelayed({
// Log.d(TAG, "onListen: send ADK from android")
//
// events?.success("ACK from android")
// }, 1000)
// }
//
// override fun onCancel(arguments: Any?) {
// Log.d(TAG, "onCancel: eventChan cancel")
// }
// })
channel.setMethodCallHandler { methodCall: MethodCall, result: MethodChannel.Result ->
if (methodCall.method == METHOD_NAME) {
val name = methodCall.argument<String>("name")
val version = methodCall.argument<String>("version")
val language = methodCall.argument<String>("language")
val androidApi = methodCall.argument<Int>("android_api")
Log.d(
TAG, "configureFlutterEngine: \n" +
"name=$name, version=$version, language=$language, androidApi=$androidApi"
)
result.success("ACK from android")
}
}
}
}