Flutter for OpenHarmony 实战:二维码生成器 - 将文本、链接等生成二维码
在移动开发领域,我们总是面临着选择与适配。今天,你的Flutter应用在Android和iOS上跑得正欢,明天可能就需要考虑一个新的平台:HarmonyOS(鸿蒙)。这不是一道选答题,而是很多团队正在面对的现实。Flutter的优势很明确——写一套代码,就能在两个主要平台上运行,开发体验流畅。而鸿蒙代表的是下一个时代的互联生态,它不仅仅是手机系统,更着眼于未来全场景的体验。
欢迎加入开源鸿蒙跨平台社区: https://openharmonycrossplatform.csdn.net
前言:跨生态开发的新机遇
在移动开发领域,我们总是面临着选择与适配。今天,你的Flutter应用在Android和iOS上跑得正欢,明天可能就需要考虑一个新的平台:HarmonyOS(鸿蒙)。这不是一道选答题,而是很多团队正在面对的现实。
Flutter的优势很明确——写一套代码,就能在两个主要平台上运行,开发体验流畅。而鸿蒙代表的是下一个时代的互联生态,它不仅仅是手机系统,更着眼于未来全场景的体验。将现有的Flutter应用适配到鸿蒙,听起来像是一个“跨界”任务,但它本质上是一次有价值的技术拓展:让产品触达更多用户,也让技术栈覆盖更广。
不过,这条路走起来并不像听起来那么简单。Flutter和鸿蒙,从底层的架构到上层的工具链,都有着各自的设计逻辑。会遇到一些具体的问题:代码如何组织?原有的功能在鸿蒙上如何实现?那些平台特有的能力该怎么调用?更实际的是,从编译打包到上架部署,整个流程都需要重新摸索。
这篇文章想做的,就是把这些我们趟过的路、踩过的坑,清晰地摊开给你看。我们不会只停留在“怎么做”,还会聊到“为什么得这么做”,以及“如果出了问题该往哪想”。这更像是一份实战笔记,源自真实的项目经验,聚焦于那些真正卡住过我们的环节。
无论你是在为一个成熟产品寻找新的落地平台,还是从一开始就希望构建能面向多端的应用,这里的思路和解决方案都能提供直接的参考。理解了两套体系之间的异同,掌握了关键的衔接技术,不仅能完成这次迁移,更能积累起应对未来技术变化的能力。
混合工程结构深度解析
项目目录架构
当Flutter项目集成鸿蒙支持后,典型的项目结构会发生显著变化。以下是经过ohos_flutter插件初始化后的项目结构:
my_flutter_harmony_app/
├── lib/ # Flutter业务代码(基本不变)
│ ├── main.dart # 应用入口
│ ├── home_page.dart # 首页
│ └── utils/
│ └── platform_utils.dart # 平台工具类
├── pubspec.yaml # Flutter依赖配置
├── ohos/ # 鸿蒙原生层(核心适配区)
│ ├── entry/ # 主模块
│ │ └── src/main/
│ │ ├── ets/ # ArkTS代码
│ │ │ ├── MainAbility/
│ │ │ │ ├── MainAbility.ts # 主Ability
│ │ │ │ └── MainAbilityContext.ts
│ │ │ └── pages/
│ │ │ ├── Index.ets # 主页面
│ │ │ └── Splash.ets # 启动页
│ │ ├── resources/ # 鸿蒙资源文件
│ │ │ ├── base/
│ │ │ │ ├── element/ # 字符串等
│ │ │ │ ├── media/ # 图片资源
│ │ │ │ └── profile/ # 配置文件
│ │ │ └── en_US/ # 英文资源
│ │ └── config.json # 应用核心配置
│ ├── ohos_test/ # 测试模块
│ ├── build-profile.json5 # 构建配置
│ └── oh-package.json5 # 鸿蒙依赖管理
└── README.md
目录
展示效果图片
flutter 实时预览 效果展示
运行到鸿蒙虚拟设备中效果展示
功能代码实现
QrCodeGenerator 组件实现
QrCodeGenerator 是一个基于 qr_flutter 库实现的二维码生成组件,具有以下特性:
- 支持自定义标题和初始数据
- 实现文本编辑功能,可实时更新二维码
- 支持点击二维码复制内容到剪贴板
- 响应式布局设计,适配不同屏幕尺寸
核心代码实现
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:qr_flutter/qr_flutter.dart';
class QrCodeGenerator extends StatefulWidget {
final String? initialData;
final double? width;
final double? height;
final Color? qrColor;
final Color? backgroundColor;
final String title;
const QrCodeGenerator({
Key? key,
this.initialData,
this.width,
this.height,
this.qrColor,
this.backgroundColor,
required this.title,
}) : super(key: key);
State<QrCodeGenerator> createState() => _QrCodeGeneratorState();
}
class _QrCodeGeneratorState extends State<QrCodeGenerator> {
late TextEditingController _controller;
late String _qrData;
bool _isEditing = false;
void initState() {
super.initState();
_qrData = widget.initialData ?? 'https://www.example.com';
_controller = TextEditingController(text: _qrData);
}
void dispose() {
_controller.dispose();
super.dispose();
}
void _updateQrCode() {
setState(() {
_qrData = _controller.text;
_isEditing = false;
});
}
void _copyToClipboard() {
Clipboard.setData(ClipboardData(text: _qrData));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('已复制到剪贴板')),
);
}
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(16.0),
padding: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12.0),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 2,
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.title,
style: const TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
const SizedBox(height: 16.0),
if (_isEditing)
Column(
children: [
TextField(
controller: _controller,
maxLines: 3,
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: '输入文本或链接',
suffixIcon: IconButton(
icon: const Icon(Icons.check),
onPressed: _updateQrCode,
),
),
),
const SizedBox(height: 12.0),
],
)
else
GestureDetector(
onTap: () {
setState(() {
_isEditing = true;
});
},
child: Container(
padding: const EdgeInsets.all(12.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(8.0),
color: Colors.grey[50],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
_qrData,
style: const TextStyle(color: Colors.black87),
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
),
const Icon(Icons.edit, color: Colors.blue),
],
),
),
),
const SizedBox(height: 24.0),
Center(
child: GestureDetector(
onTap: _copyToClipboard,
child: Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: widget.backgroundColor ?? Colors.white,
borderRadius: BorderRadius.circular(8.0),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 1,
blurRadius: 4,
offset: const Offset(0, 1),
),
],
),
child: QrImageView(
data: _qrData,
version: QrVersions.auto,
size: widget.width ?? 200.0,
gapless: false,
eyeStyle: const QrEyeStyle(
eyeShape: QrEyeShape.square,
color: Colors.black87,
),
dataModuleStyle: QrDataModuleStyle(
dataModuleShape: QrDataModuleShape.square,
color: widget.qrColor ?? Colors.black87,
),
),
),
),
),
const SizedBox(height: 16.0),
Center(
child: Text(
'点击二维码复制内容',
style: TextStyle(
fontSize: 14.0,
color: Colors.grey[600],
),
),
),
],
),
);
}
}
主页面集成
在 main.dart 文件中,我们集成了两个 QrCodeGenerator 组件,分别用于生成文本二维码和链接二维码:
import 'package:flutter/material.dart';
import 'package:aa/widgets/qr_code_generator.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter for openHarmony',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
debugShowCheckedModeBanner: false,
home: const MyHomePage(title: 'Flutter for openHarmony'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
QrCodeGenerator(
title: '文本二维码',
initialData: 'Hello, Flutter for OpenHarmony!',
width: 250,
height: 250,
),
const SizedBox(height: 40),
QrCodeGenerator(
title: '链接二维码',
initialData: 'https://www.openharmony.cn/',
width: 250,
height: 250,
qrColor: Colors.blue,
backgroundColor: Colors.white,
),
],
),
),
);
}
}
本次开发中容易遇到的问题
-
依赖管理问题
- 问题:缺少 qr_flutter 依赖会导致二维码生成功能无法实现
- 解决方案:在 pubspec.yaml 文件中添加 qr_flutter: ^4.1.0 依赖,并执行 flutter pub get 命令更新依赖
-
文本编辑状态管理
- 问题:在编辑文本时,需要正确管理编辑状态和二维码更新
- 解决方案:使用 StatefulWidget 和 setState 管理编辑状态,在用户确认编辑后更新二维码数据
-
剪贴板操作权限
- 问题:在不同平台上,剪贴板操作可能需要不同的权限处理
- 解决方案:使用 Flutter 内置的 Clipboard 类,它会自动处理跨平台的权限问题
-
二维码大小适配
- 问题:在不同屏幕尺寸下,二维码大小可能需要调整
- 解决方案:为组件提供可自定义的 width 和 height 参数,默认值设为适合大多数屏幕的尺寸
-
初始数据处理
- 问题:如果用户未提供初始数据,需要设置合理的默认值
- 解决方案:使用 late 关键字和 initState 方法,为初始数据设置默认值
总结本次开发中用到的技术点
-
Flutter 状态管理
- 使用 StatefulWidget 和 setState 管理组件状态,实现文本编辑和二维码更新功能
- 通过状态变量 _isEditing 跟踪当前编辑状态
-
Flutter 布局系统
- 使用 Container、Column、Expanded 等布局组件构建响应式界面
- 运用 BoxDecoration 实现卡片阴影效果,提升视觉体验
-
qr_flutter 库
- 基于 qr_flutter 库实现二维码渲染
- 配置 QrImageView 参数实现自定义二维码效果,包括颜色、大小等
-
用户交互
- 实现文本编辑功能,支持用户输入自定义内容
- 实现二维码点击事件处理,复制内容到剪贴板
- 使用 ScaffoldMessenger 显示 SnackBar 提示信息
-
数据处理
- 使用 TextEditingController 管理文本输入
- 处理初始数据的默认值设置
-
代码组织
- 采用组件化开发方式,将二维码生成封装为独立的 QrCodeGenerator 组件
- 分离业务逻辑和 UI 展示,提高代码可维护性
-
跨平台适配
- 选择跨平台兼容性好的 qr_flutter 库,避免平台特定依赖
- 确保代码在 Flutter 支持的所有平台(包括 OpenHarmony)上正常运行
-
响应式设计
- 使用 SingleChildScrollView 实现可滚动布局,适配不同屏幕尺寸
- 为组件提供可自定义的宽高参数,增强灵活性
欢迎加入开源鸿蒙跨平台社区: https://openharmonycrossplatform.csdn.net
更多推荐





所有评论(0)