Flutter框架跨平台鸿蒙开发——Pattern Matching模式匹配

一、Pattern Matching概述

Pattern Matching提供了一种声明式的方式来处理数据结构。




表达式
匹配Pattern
是否匹配?
执行对应分支
尝试下一分支
还有分支?
执行默认分支
返回结果

|| 特性 | 说明 |

|------|------|

| 声明式 | 代码更清晰 |

| 类型安全 | 编译时检查 |

| 解构支持 | 同时匹配和提取 |

| 多层次 | 支持嵌套匹配 |

二、示例代码

dart 复制代码
class _Page04PatternDemo extends StatefulWidget {
  const _Page04PatternDemo();

  @override
  State<_Page04PatternDemo> createState() => _Page04PatternDemoState();
}

class _Page04PatternDemoState extends State<_Page04PatternDemo> {
  String _input = 'user:123';
  String _result = '';

  void _analyzeInput() {
    setState(() {
      _result = _analyzeUserInput(_input);
    });
  }

  String _analyzeUserInput(String input) {
    switch (input) {
      case 'admin':
        return '管理员权限';
      case final s when s.startsWith('user:'):
        return '用户ID: ${s.split(':')[1]}';
      case final s when s.startsWith('guest:'):
        return '访客: ${s.split(':')[1]}';
      case '':
        return '空输入';
      default:
        return '未知输入';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.green.shade50,
      padding: const EdgeInsets.all(20),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: Colors.green.shade600,
              borderRadius: BorderRadius.circular(20),
            ),
            child: const Column(
              children: [
                Icon(Icons.pattern, size: 48, color: Colors.white),
                SizedBox(height: 16),
                Text(
                  'Pattern Matching',
                  style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.white),
                ),
                SizedBox(height: 8),
                Text('模式匹配 - 页面 4/5', style: TextStyle(color: Colors.white70)),
              ],
            ),
          ),
          const SizedBox(height: 24),
          Expanded(
            child: Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20)),
              child: Column(
                children: [
                  TextField(
                    decoration: InputDecoration(
                      labelText: '输入用户信息',
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
                      hintText: '试试: admin, user:123, guest:456',
                    ),
                    onChanged: (value) => _input = value,
                  ),
                  const SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: _analyzeInput,
                    style: ElevatedButton.styleFrom(backgroundColor: Colors.green.shade600),
                    child: const Text('分析', style: TextStyle(color: Colors.white)),
                  ),
                  const SizedBox(height: 20),
                  if (_result.isNotEmpty)
                    Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.green.shade100,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(_result, style: const TextStyle(fontSize: 18)),
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

三、匹配流程









输入
匹配admin?
返回管理员权限
以user:开头?
提取并返回用户ID
以guest:开头?
返回访客信息
是空字符串?
返回空输入
返回未知输入

四、Pattern类型

Pattern 说明 示例
常量模式 匹配固定值 case 42:
变量模式 匹配任意值并绑定 case var x:
通配符模式 匹配任意值不绑定 case _:
记录模式 解构Record case (a, b):

五、最佳实践

  • ✅ 从具体到抽象排列case
  • ✅ 使用守卫条件提高精度
  • ✅ 充分利用解构
  • ❌ 避免过度嵌套

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

相关推荐
海鸥两三2 小时前
登录页面form表单
前端·javascript·css
世人万千丶2 小时前
鸿蒙跨端框架 Flutter 学习:GetX 全家桶:从状态管理到路由导航的极简艺术
学习·flutter·ui·华为·harmonyos·鸿蒙
侧耳4292 小时前
android9_box hdmi铺不满的问题
android·java
dazhong20122 小时前
Android Studio WIFI 无线调试
android·ide·android studio
夜雨声烦丿2 小时前
Flutter 框架跨平台鸿蒙开发 - 电影票房查询 - 完整开发教程
flutter·华为·harmonyos
践行见远2 小时前
django之序列化
android·数据库·django
summerkissyou19872 小时前
Android13-蓝牙-发现,配对,连接-例子
android·蓝牙
游戏开发爱好者82 小时前
iOS App 抓不到包时的常见成因与判断思路,结合iOS 调试经验
android·ios·小程序·https·uni-app·iphone·webview
小白阿龙3 小时前
鸿蒙+flutter 跨平台开发——从零打造手持弹幕App实战
flutter·华为·harmonyos·鸿蒙