Flutter谷歌Material设计系统实现插件google_matter_flutter的使用
Flutter谷歌Material设计系统实现插件google_matter_flutter的使用
可用功能:
- 委托一个Matter设备。
- 获取设备事件(仅限布尔值)。
不可用功能:
- 获取其他类型的事件。
- 发送命令到设备。
- 在注册时设置设备类型。
请注意,该插件仍在开发中,许多API尚未可用。库也不稳定,并且当处理未处理的设备时可能会崩溃。如果您能帮助解决上述问题,请随时为项目做出贡献。
使用方法
-
将
google_matter_flutter
添加为您的pubspec.yaml
文件中的依赖项。 -
下载
sample-app-for-matter-android-codelab.zip
文件,可以从这里下载。 -
下载后解压文件,并导航到
sample-app-for-matter-android-codelab/app
目录。 -
您会发现一个名为
third_party
的文件夹。将此文件夹复制并粘贴到项目的android
目录下。 -
在您的
AndroidManifest.xml
文件中添加以下内容:
在Activity
标签内:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.google.android.gms.home.matter.ACTION_COMMISSION_DEVICE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
在Application
标签内:
<service
android:name="com.google.google_matter_flutter.google_matter_flutter.AppCommissioningService"
android:exported="true" />
示例代码
以下是完整的示例代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:google_matter_flutter/google_matter_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final GoogleMatterFlutter _googleMatterFlutterPlugin = GoogleMatterFlutter();
bool isCommissioningInProgress = false;
// 加载已委托的Matter设备
Future<List<MatterDevice>> loadMatterDevices() async {
final prefs = await SharedPreferences.getInstance();
final List matterDevicesList =
jsonDecode(prefs.getString("matterDevices") ?? "[]");
return matterDevicesList
.map((e) => MatterDevice.fromJson(e as Map))
.toList();
}
// 添加已委托的Matter设备
Future<void> addMatterDevice(MatterDevice matterDevice) async {
final prefs = await SharedPreferences.getInstance();
final List<MatterDevice> matterDevices = await loadMatterDevices();
matterDevices.add(matterDevice);
final List matterDevicesList =
matterDevices.map((e) => e.toJson()).toList();
prefs.setString("matterDevices", jsonEncode(matterDevicesList));
}
// 删除已委托的Matter设备
Future<void> removeMatterDevice(MatterDevice matterDevice) async {
final prefs = await SharedPreferences.getInstance();
final List<MatterDevice> matterDevices = await loadMatterDevices();
matterDevices
.removeWhere((device) => device.deviceId == matterDevice.deviceId);
final List matterDevicesList =
matterDevices.map((e) => e.toJson()).toList();
prefs.setString("matterDevices", jsonEncode(matterDevicesList));
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSwatch(
brightness: Brightness.dark,
primarySwatch: Colors.deepPurple,
),
),
darkTheme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSwatch(
brightness: Brightness.dark,
primarySwatch: Colors.deepPurple,
),
),
home: Scaffold(
appBar: AppBar(
title: const Text('Google Matter 示例应用'),
),
body: FutureBuilder<List<MatterDevice>>(
future: loadMatterDevices(),
builder: (BuildContext context, AsyncSnapshot<List<MatterDevice>> snapshot) {
if (snapshot.data == null) {
return const Center(child: CircularProgressIndicator());
}
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, int index) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
"设备名称: ${snapshot.data![index].deviceName}",
style: Theme.of(context).textTheme.titleLarge,
maxLines: 3,
),
),
IconButton(
onPressed: () async {
// 删除此设备
await removeMatterDevice(snapshot.data![index]);
setState(() {});
},
icon: const Icon(Icons.delete),
)
],
),
const SizedBox(height: 4),
Text(
"设备ID: ${snapshot.data![index].deviceId}",
style: Theme.of(context).textTheme.bodyLarge,
),
Text(
"厂商ID: ${snapshot.data![index].vendorId}",
style: Theme.of(context).textTheme.bodyLarge,
),
Text(
"设备类型: ${snapshot.data![index].deviceType}",
style: Theme.of(context).textTheme.bodyLarge,
),
if (!isCommissioningInProgress)
StreamBuilder<bool?>(
stream: snapshot.data![index].listenToEvents(),
builder: (context, snapshot) {
return Text(
"值: ${snapshot.data ?? "离线"}",
style: Theme.of(context).textTheme.bodyLarge,
);
}),
],
),
),
);
},
);
},
),
floatingActionButton: FloatingActionButton.large(
child: const Icon(Icons.add),
onPressed: () async {
try {
setState(() {
isCommissioningInProgress = true;
});
final MatterDevice? device =
await _googleMatterFlutterPlugin.commissionDevice();
if (device != null) {
await addMatterDevice(device);
setState(() {
isCommissioningInProgress = false;
});
}
} catch (ex) {
setState(() {
isCommissioningInProgress = false;
});
print('未能获取委托: $ex');
}
},
),
),
);
}
}
更多关于Flutter谷歌Material设计系统实现插件google_matter_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter谷歌Material设计系统实现插件google_matter_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,google_matter_flutter
插件(注意:在撰写此回复时,google_matter_flutter
并非一个官方或广泛认可的插件名称,但假设它是用于实现Google新的Matter设计系统的插件)可以帮助开发者快速采用和集成Matter设计系统。以下是一个假设性的示例代码,展示了如何使用一个类似命名的插件(如果它存在)来创建一个符合Matter设计规范的按钮。
首先,确保在pubspec.yaml
文件中添加依赖项(注意:实际插件名和版本号需要根据实际情况调整):
dependencies:
flutter:
sdk: flutter
google_matter_flutter: ^x.y.z # 假设的版本号
然后运行flutter pub get
来安装依赖。
接下来,在你的Dart代码中,你可以这样使用google_matter_flutter
来创建一个按钮:
import 'package:flutter/material.dart';
import 'package:google_matter_flutter/google_matter_flutter.dart'; // 假设的导入路径
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Google Matter Design Example',
theme: ThemeData(
// 使用Matter主题(这里假设插件提供了预设的主题)
primarySwatch: MatterColors.primary, // 假设MatterColors是插件提供的一个颜色类
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Matter Design Button Example'),
),
body: Center(
child: MatterButton(
onPressed: () {
// 按钮点击事件
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Button pressed!')),
);
},
child: Text('Matter Button'),
),
),
);
}
}
// 假设MatterButton是插件提供的一个按钮组件
// 如果插件没有提供,你可能需要自己实现一个符合Matter设计的按钮
class MatterButton extends StatelessWidget {
final VoidCallback? onPressed;
final Widget child;
const MatterButton({Key? key, required this.onPressed, required this.child})
: super(key: key);
@override
Widget build(BuildContext context) {
return ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
),
),
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return MatterColors.primary.withOpacity(0.7); // 假设的按压颜色
}
return MatterColors.primary; // 假设的主颜色
},
),
overlayColor: MaterialStateProperty.resolveWith<Color?>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.hover)) {
return MatterColors.primary.withOpacity(0.12); // 假设的悬停颜色
}
return null;
},
),
),
onPressed: onPressed,
child: child,
);
}
}
// 假设MatterColors是插件提供的一个颜色类,如果没有,你需要自己定义颜色
class MatterColors {
static const Color primary = Color(0xFF1A73E8); // 假设的主颜色
// 可以添加更多颜色...
}
请注意,上述代码是一个示例,假设google_matter_flutter
插件提供了MatterButton
和MatterColors
等组件和颜色类。实际上,如果这样的插件存在,它的API可能会有所不同,你需要参考插件的官方文档来获取准确的使用方法和组件。
如果google_matter_flutter
插件不存在,你可能需要自己根据Matter设计指南实现自定义的组件和主题。Flutter的Material
组件库非常灵活,允许开发者通过自定义主题、形状、颜色等来创建符合特定设计系统的UI。