zh_native_channel 0.0.6
zh_native_channel: ^0.0.6 copied to clipboard
Reusable platform channel message framework for Flutter.
example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:zh_native_channel/zh_native_channel.dart';
import 'package:zh_native_channel_example/base/zHNativeChannel/msgs/UserMsg.dart';
import 'base/zHNativeChannel/ChannelGeneratedRegister.g.dart';
import 'base/zHNativeChannel/msgs/ping_msg.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
initializeGeneratedChannels();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ZH Native Channel Example',
theme: ThemeData(colorScheme: .fromSeed(seedColor: Colors.deepPurple)),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _result = '尚未调用';
String _nestedResult = '尚未调用';
Future<void> _sendPing() async {
setState(() {
_result = '调用中...';
});
try {
final response = await ZHNativeChannel.instance.invoke(PingMsg(text: 'hello'));
final ping = response as PingMsg;
setState(() {
_result = ping.text;
});
} catch (error) {
setState(() {
_result = '调用失败: $error';
});
}
}
Future<void> _sendNestedMsg() async {
setState(() {
_nestedResult = '调用中...';
});
try {
final response = await ZHNativeChannel.instance.invoke(
UserMsg(
name: '',
age: 0,
preferences: Preferences(
name: '',
address: Address(street: '', city: '', state: '', zip: ''),
),
),
);
final user = response as UserMsg;
setState(() {
print("---- get nested result: ${user.toMap()}");
_nestedResult = user.toMap().toString();
});
} catch (error) {
setState(() {
_nestedResult = '调用失败: $error';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('ZH Native Channel Example'),
),
body: Center(
child: Column(
mainAxisAlignment: .center,
children: [
const Text('点击按钮向原生发送 PingMsg'),
const SizedBox(height: 16),
Text(_result, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 24),
FilledButton(onPressed: _sendPing, child: const Text('发送 Ping')),
const SizedBox(height: 24),
Text(_nestedResult, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 24),
FilledButton(onPressed: _sendNestedMsg, child: const Text('发送嵌套消息')),
],
),
),
);
}
}