Skip to Content

33b - AI 辅助跨平台移动开发

本文是《AI Agent 实战手册》第 33 章第 2 节。 上一节:33a-AI辅助移动端开发概览 | 下一节:33c-原生模块开发

概述

跨平台移动开发在 AI 时代迎来了质的飞跃——Bolt.new + Expo 让”对话即应用”成为现实,Cursor + 规则文件让 Flutter 开发效率倍增,Claude Code 的全项目理解能力让 React Native 大型项目重构变得轻松。本节深入覆盖 React Native + Expo、Flutter、以及 Expo 生态系统的 AI 辅助开发实践,包括组件生成模式、导航配置、状态管理、平台特定处理,以及完整的提示词模板和实战案例,帮助跨平台开发者建立系统化的 AI 辅助开发工作流。


1. 跨平台开发 AI 工具链

1.1 AI 辅助跨平台开发工具推荐

工具用途支持框架价格适用场景
Bolt.new + Expo对话生成完整移动应用React Native + Expo免费(基础)/ $20/月(Pro)/ $40/月(Team)快速 MVP、非技术用户构建移动应用
CursorAI-first IDE,多文件编辑React Native / Flutter / 全部免费 / $20/月(Pro)/ $40/月(Ultra)专业跨平台开发,需要规则文件定制
Claude CodeCLI 全项目理解与自主编码React Native / Flutter / 全部$20/月(Max 5x)/ API 按量大型项目重构,自动化工作流
FlutterFlow / Dreamflow可视化 + AI 辅助 Flutter 构建Flutter免费 / $30/月(Standard)/ $70/月(Pro)Flutter 可视化构建,快速原型
FastshotAI 驱动移动应用生成器React Native$29/月起快速原型,创业者 MVP
RapidNativeAI 生成生产级 RN UI 屏幕React Native免费(基础)/ $19/月(Pro)设计到代码,UI 屏幕快速生成
Firebase StudioGoogle AI 应用构建 + Firebase 后端Flutter / React免费(预览期)Google 生态用户,需要 Firebase 后端
KiroSpec 驱动开发 + Steering 规则React Native / Flutter / 全部免费(预览期)结构化移动端开发,团队协作
GitHub CopilotIDE 插件,行级补全 + Agent 模式全部$10/月 / $19/月(Business)企业团队标准化,多 IDE 用户
Rork AI专注移动应用的 Vibe Coding 平台React Native + Expo免费 / 付费计划纯对话式移动应用构建

1.2 工具选择决策矩阵

你的需求是什么? ├─ 5 分钟内看到可运行的移动应用原型 │ └─→ Bolt.new + Expo / Rork AI │ 适合:验证想法、演示、非技术创始人 ├─ 专业级跨平台开发(React Native) │ ├─ 偏好 CLI 工作流 → Claude Code + Expo │ └─ 偏好 IDE 工作流 → Cursor + 规则文件 │ 适合:全职移动端开发者、中大型项目 ├─ 专业级跨平台开发(Flutter) │ ├─ 偏好代码优先 → Cursor + Flutter 规则文件 │ └─ 偏好可视化 → FlutterFlow / Dreamflow │ 适合:Dart 开发者、需要高度自定义 UI └─ Spec 驱动的结构化开发 └─→ Kiro + Steering 规则 适合:团队项目、需要需求追踪

2. React Native + Expo:AI 辅助开发深度指南

2.1 为什么 React Native + Expo 是 AI 辅助移动开发的首选

React Native + Expo 在 AI 辅助开发中占据绝对优势,原因如下:

  1. AI 训练数据最丰富:JavaScript/TypeScript 是 LLM 训练数据中占比最大的语言,React 组件模式被 AI 深度理解
  2. Bolt.new + Expo 生态:2025 年 2 月 Bolt.new 集成 Expo 后,实现了浏览器内生成移动应用并直接部署
  3. Expo 屏蔽原生复杂性:托管工作流让 AI 专注于业务逻辑,无需处理 Xcode/Gradle 配置
  4. 即时预览:Expo Go 提供秒级预览,缩短 AI 迭代的反馈循环
  5. OTA 更新:EAS Update 支持热更新,绕过 App Store 审核周期
  6. 丰富的 Claude Code Skills:社区已有成熟的 React Native + Expo Skills(如 react-native-expo skill 覆盖 SDK 52-54)

2.2 Expo 项目初始化:AI 辅助工作流

方式一:Bolt.new 快速原型(5 分钟)

Bolt.new 集成 Expo 后,可以在浏览器内直接生成完整的 React Native 移动应用。

操作步骤:

  1. 访问 bolt.new ,选择 Expo 模板
  2. 用自然语言描述应用需求
  3. AI 自动生成完整项目(包含导航、组件、样式)
  4. 在浏览器内预览,或通过 Expo Go 扫码在手机上预览
  5. 导出代码到本地,继续在 Cursor / Claude Code 中开发

提示词模板:Bolt.new 移动应用生成

创建一个 [应用类型] 移动应用,使用 React Native + Expo SDK 54,包含以下功能: ## 核心功能 1. [功能 1 描述] 2. [功能 2 描述] 3. [功能 3 描述] ## 设计要求 - 使用 [深色/浅色/自适应] 主题 - 底部 Tab 导航,包含 [N] 个 Tab:[Tab1]、[Tab2]、[Tab3] - 遵循 iOS Human Interface Guidelines 和 Android Material Design 3 - 支持 Dark Mode 切换 ## 技术要求 - 使用 expo-router 进行文件系统路由 - 使用 [Zustand/Jotai] 进行状态管理 - TypeScript 严格模式 - 所有组件支持无障碍标签

Bolt.new 生成质量评估:

维度质量评级说明
UI 布局★★★★☆基础布局准确,复杂布局需手动调整
导航配置★★★★★expo-router 配置通常正确
状态管理★★★☆☆简单状态可用,复杂状态需重构
平台适配★★★☆☆基础适配有,深度平台差异需手动处理
TypeScript 类型★★★☆☆基础类型有,严格类型需补充
性能优化★★☆☆☆缺少虚拟化列表、memo 等优化
测试代码★☆☆☆☆通常不生成测试

关键洞察:Bolt.new 适合生成 60-70% 的初始代码,剩余部分需要在专业 IDE 中用 AI 辅助完善。

方式二:Claude Code + Expo 专业初始化

# 1. 创建 Expo 项目 npx create-expo-app@latest my-app --template tabs # 2. 进入项目目录,启动 Claude Code cd my-app claude # 3. 在 Claude Code 中描述需求

Claude Code 初始化提示词:

我刚创建了一个 Expo 项目(tabs 模板)。请帮我完成以下初始化配置: 1. 项目结构重组: - app/(expo-router 路由) - components/(可复用组件) - hooks/(自定义 hooks) - stores/(Zustand 状态管理) - services/(API 服务层) - constants/(常量和配置) - types/(TypeScript 类型定义) 2. 基础配置: - 配置 TypeScript 严格模式 - 设置路径别名(@/ 指向项目根目录) - 配置 ESLint + Prettier - 设置主题系统(支持 Dark Mode) 3. 导航结构: - 底部 Tab:[首页]、[搜索]、[消息]、[我的] - 每个 Tab 内使用 Stack 导航 - 配置 Deep Linking 4. 基础组件: - 创建 ThemedText、ThemedView 等主题感知组件 - 创建 LoadingSpinner、ErrorBoundary 等通用组件 请逐步执行,每步完成后等我确认再继续。

方式三:Cursor + 规则文件专业开发

在 Cursor 中使用 React Native 专用规则文件,可以显著提升 AI 生成代码的质量。

React Native + Expo 规则文件示例(.cursor/rules/react-native.mdc):

--- description: React Native + Expo 开发规则 globs: ["**/*.tsx", "**/*.ts", "app/**/*"] --- # React Native + Expo 开发规范 ## 技术栈 - React Native 0.76+ / Expo SDK 54 - TypeScript 严格模式 - expo-router(文件系统路由) - Zustand(状态管理) - react-native-reanimated(动画) - expo-image(图片加载) ## 组件规范 - 所有组件使用函数式组件 + TypeScript - Props 接口命名:`{ComponentName}Props` - 纯展示组件使用 React.memo - 长列表使用 FlashList 而非 FlatList - 可点击区域最小 44x44pt - 所有可交互元素必须有 accessibilityLabel ## 样式规范 - 使用 StyleSheet.create 而非内联样式 - 支持 Dark Mode(使用 useColorScheme) - 间距使用 8pt 网格系统 - 字体大小支持 Dynamic Type ## 导航规范 - 使用 expo-router 文件系统路由 - Tab 导航使用 app/(tabs)/ 目录结构 - Stack 导航使用 _layout.tsx 配置 - 所有路由支持 Deep Linking ## 性能规范 - 禁止在 ScrollView 中嵌套 FlatList - 图片使用 expo-image 并设置 placeholder - 网络请求使用 @tanstack/react-query - 避免在渲染函数中创建新对象/函数 - 使用 useMemo/useCallback 优化重渲染 ## 安全规范 - 敏感数据使用 expo-secure-store - 所有网络请求使用 HTTPS - 禁止硬编码 API 密钥 - 使用环境变量管理配置

2.3 AI 辅助组件生成(React Native)

2.3.1 基础组件生成模式

提示词模板:React Native 组件生成

请为 React Native + Expo 生成一个 [组件名称] 组件: ## 功能需求 [详细描述组件功能] ## 视觉规格 - 布局:[Flex 布局描述] - 颜色:使用主题系统(支持 Dark Mode) - 间距:8pt 网格 - 字体:[字体规格] - 圆角:[圆角值] ## 交互行为 - [交互 1 描述] - [交互 2 描述] - 动画:使用 react-native-reanimated ## Props 接口 - [prop1]: [类型] - [描述] - [prop2]: [类型] - [描述] - onPress?: () => void ## 无障碍要求 - accessibilityLabel: [描述] - accessibilityRole: [角色] - 支持 VoiceOver / TalkBack ## 平台差异 - iOS:[iOS 特定行为] - Android:[Android 特定行为]

示例:生成一个用户资料卡片组件

请为 React Native + Expo 生成一个 UserProfileCard 组件: ## 功能需求 显示用户头像、昵称、简介和关注按钮。支持加载状态和错误状态。 ## 视觉规格 - 布局:水平排列,头像在左,信息在右 - 头像:48x48 圆形,使用 expo-image - 昵称:16px 粗体 - 简介:14px 灰色,最多 2 行 - 关注按钮:右侧,胶囊形状 ## 交互行为 - 点击头像:导航到用户详情页 - 点击关注按钮:切换关注状态,带 haptic 反馈 - 长按:显示操作菜单 ## Props 接口 - user: { id: string; name: string; avatar: string; bio: string } - isFollowing: boolean - onFollowToggle: (userId: string) => void - onPress: (userId: string) => void ## 平台差异 - iOS:使用 SF Symbols 图标,Haptic 反馈使用 expo-haptics - Android:使用 Material Icons,Haptic 反馈使用 Vibration API

AI 生成的组件代码示例:

// components/UserProfileCard.tsx import { memo, useCallback } from 'react'; import { StyleSheet, View, Text, Pressable, Platform, } from 'react-native'; import { Image } from 'expo-image'; import * as Haptics from 'expo-haptics'; import { useRouter } from 'expo-router'; import { useThemeColor } from '@/hooks/useThemeColor'; interface UserProfileCardProps { user: { id: string; name: string; avatar: string; bio: string; }; isFollowing: boolean; onFollowToggle: (userId: string) => void; onPress?: (userId: string) => void; } function UserProfileCard({ user, isFollowing, onFollowToggle, onPress, }: UserProfileCardProps) { const router = useRouter(); const textColor = useThemeColor('text'); const subtextColor = useThemeColor('subtext'); const primaryColor = useThemeColor('primary'); const cardBg = useThemeColor('card'); const handlePress = useCallback(() => { onPress?.(user.id); }, [user.id, onPress]); const handleFollowToggle = useCallback(async () => { if (Platform.OS === 'ios') { await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); } onFollowToggle(user.id); }, [user.id, onFollowToggle]); const handleAvatarPress = useCallback(() => { router.push(`/user/${user.id}`); }, [user.id, router]); return ( <Pressable style={[styles.container, { backgroundColor: cardBg }]} onPress={handlePress} accessibilityLabel={`${user.name} 的个人资料`} accessibilityRole="button" > <Pressable onPress={handleAvatarPress}> <Image source={{ uri: user.avatar }} style={styles.avatar} placeholder="L6PZfSi_.AyE_3t7t7R**0o#DgR4" contentFit="cover" transition={200} accessibilityLabel={`${user.name} 的头像`} /> </Pressable> <View style={styles.info}> <Text style={[styles.name, { color: textColor }]} numberOfLines={1} > {user.name} </Text> <Text style={[styles.bio, { color: subtextColor }]} numberOfLines={2} > {user.bio} </Text> </View> <Pressable style={[ styles.followButton, isFollowing ? styles.followingButton : { backgroundColor: primaryColor }, ]} onPress={handleFollowToggle} accessibilityLabel={isFollowing ? '取消关注' : '关注'} accessibilityRole="button" hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }} > <Text style={[ styles.followText, isFollowing && styles.followingText, ]} > {isFollowing ? '已关注' : '关注'} </Text> </Pressable> </Pressable> ); } export default memo(UserProfileCard); const styles = StyleSheet.create({ container: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 12, marginHorizontal: 16, marginVertical: 4, }, avatar: { width: 48, height: 48, borderRadius: 24, }, info: { flex: 1, marginLeft: 12, marginRight: 12, }, name: { fontSize: 16, fontWeight: '600', marginBottom: 2, }, bio: { fontSize: 14, lineHeight: 18, }, followButton: { paddingHorizontal: 16, paddingVertical: 8, borderRadius: 20, minWidth: 72, alignItems: 'center', minHeight: 44, justifyContent: 'center', }, followingButton: { backgroundColor: 'transparent', borderWidth: 1, borderColor: '#ccc', }, followText: { color: '#fff', fontSize: 14, fontWeight: '600', }, followingText: { color: '#666', }, });

代码审查要点

AI 生成的这个组件遵循了以下最佳实践:

  • ✅ 使用 memo 包裹纯展示组件
  • ✅ 使用 useCallback 避免不必要的重渲染
  • ✅ 使用 expo-image 替代 Image(支持缓存和 placeholder)
  • ✅ 所有可交互元素有 accessibilityLabel
  • ✅ 按钮最小触摸区域 44pt(通过 minHeighthitSlop
  • ✅ 使用主题系统支持 Dark Mode
  • ✅ 平台特定的 Haptic 反馈处理

2.3.2 设计稿到组件的 AI 工作流

截图到代码(Screenshot-to-Code)

我有一张移动端 UI 设计截图。请分析这张截图并生成对应的 React Native + Expo 组件代码。 ## 要求 1. 精确还原设计稿的布局、间距、颜色 2. 使用 StyleSheet.create 管理样式 3. 所有颜色值使用主题变量 4. 图片使用 expo-image 5. 图标使用 @expo/vector-icons 6. 支持 Dark Mode(分析设计稿的配色方案推断暗色版本) 7. 添加完整的 TypeScript 类型 8. 添加无障碍标签 ## 输出格式 - 组件文件:components/[ComponentName].tsx - 类型文件:types/[componentName].ts(如果类型复杂) - 使用示例:展示如何在页面中使用该组件

Figma 到代码工作流

┌──────────────────────────────────────────────────────────────┐ │ Figma → React Native 组件工作流 │ ├──────────────────────────────────────────────────────────────┤ │ │ │ 1. Figma 设计稿 │ │ ├─ 使用 Auto Layout(对应 Flexbox) │ │ ├─ 使用 Design Tokens(对应主题变量) │ │ └─ 组件命名遵循 PascalCase │ │ │ │ 2. 导出设计信息 │ │ ├─ 方式 A:Figma Make → 直接生成 RN 代码 │ │ ├─ 方式 B:截图 → AI 识别 → 生成代码 │ │ └─ 方式 C:手动描述 → AI 生成代码 │ │ │ │ 3. AI 生成组件 │ │ ├─ Cursor / Claude Code 生成组件代码 │ │ ├─ 自动应用项目主题系统 │ │ └─ 自动添加无障碍标签 │ │ │ │ 4. 验证与调整 │ │ ├─ Expo Go 即时预览 │ │ ├─ 与设计稿对比调整 │ │ └─ 跨平台验证(iOS + Android) │ │ │ └──────────────────────────────────────────────────────────────┘

2.3.3 自然语言到组件的生成模式

复杂表单组件生成

请生成一个 React Native + Expo 的注册表单组件,包含: ## 表单字段 1. 用户名(文本输入,3-20 字符,仅字母数字下划线) 2. 邮箱(邮箱格式验证) 3. 密码(至少 8 位,包含大小写字母和数字) 4. 确认密码(与密码一致) 5. 手机号(可选,中国手机号格式) 6. 同意条款(复选框) ## 交互要求 - 实时验证,输入时显示错误提示 - 密码强度指示器(弱/中/强) - 密码可见性切换按钮 - 提交时全量验证 - 提交中显示 loading 状态 - 键盘自动避让(KeyboardAvoidingView) - 点击空白区域收起键盘 ## 技术要求 - 使用 react-hook-form + zod 进行表单管理和验证 - 使用 expo-haptics 在验证错误时提供触觉反馈 - 支持 iOS 和 Android 的键盘行为差异 - 所有输入框支持无障碍

列表组件生成

请生成一个高性能的商品列表组件,使用 React Native + Expo: ## 功能需求 - 瀑布流布局(2 列) - 下拉刷新 - 上拉加载更多 - 骨架屏加载状态 - 空状态展示 - 错误状态展示 + 重试按钮 ## 性能要求 - 使用 FlashList 而非 FlatList - 图片懒加载 + 缓存(expo-image) - 列表项使用 memo 优化 - 预估 item 高度以优化滚动性能 - 支持 1000+ 条数据流畅滚动 ## 数据获取 - 使用 @tanstack/react-query 的 useInfiniteQuery - 每页 20 条 - 支持离线缓存

2.4 expo-router 导航配置:AI 辅助指南

expo-router 是 Expo 推荐的文件系统路由方案,AI 对其支持非常成熟。

2.4.1 基础导航结构

提示词模板:导航配置生成

请为我的 Expo 应用配置 expo-router 导航结构: ## 应用结构 - 未登录:引导页 → 登录/注册 - 已登录:底部 Tab 导航 - Tab 1:[首页](Stack 导航:列表 → 详情) - Tab 2:[发现](Stack 导航:搜索 → 结果 → 详情) - Tab 3:[消息](Stack 导航:消息列表 → 聊天) - Tab 4:[我的](Stack 导航:个人中心 → 设置 → 各设置项) - 全局 Modal:分享、举报、图片预览 ## 要求 1. 生成完整的 app/ 目录结构 2. 每个 _layout.tsx 包含正确的导航配置 3. 实现认证守卫(未登录重定向到登录页) 4. 配置 Deep Linking scheme 5. 使用 Typed Routes 6. Tab 图标使用 @expo/vector-icons

AI 生成的目录结构示例:

app/ ├── _layout.tsx # 根布局:认证守卫 + 全局 Provider ├── (auth)/ # 认证路由组 │ ├── _layout.tsx # Stack 导航 │ ├── welcome.tsx # 引导页 │ ├── login.tsx # 登录页 │ └── register.tsx # 注册页 ├── (tabs)/ # Tab 路由组(需要登录) │ ├── _layout.tsx # Tab 导航配置 │ ├── index.tsx # 首页(Tab 1) │ ├── discover.tsx # 发现(Tab 2) │ ├── messages.tsx # 消息(Tab 3) │ └── profile.tsx # 我的(Tab 4) ├── home/ # 首页 Stack 子页面 │ └── [id].tsx # 详情页(动态路由) ├── discover/ │ ├── search.tsx # 搜索页 │ └── [id].tsx # 搜索结果详情 ├── chat/ │ └── [conversationId].tsx # 聊天页 ├── settings/ │ ├── index.tsx # 设置主页 │ ├── account.tsx # 账号设置 │ └── notifications.tsx # 通知设置 ├── (modals)/ # Modal 路由组 │ ├── share.tsx # 分享 Modal │ ├── report.tsx # 举报 Modal │ └── image-viewer.tsx # 图片预览 Modal └── +not-found.tsx # 404 页面

AI 生成的根布局代码:

// app/_layout.tsx import { useEffect } from 'react'; import { Stack } from 'expo-router'; import { StatusBar } from 'expo-status-bar'; import { ThemeProvider, useTheme } from '@/providers/ThemeProvider'; import { AuthProvider, useAuth } from '@/providers/AuthProvider'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import * as SplashScreen from 'expo-splash-screen'; import { useFonts } from 'expo-font'; SplashScreen.preventAutoHideAsync(); const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 60 * 1000, // 5 分钟 gcTime: 30 * 60 * 1000, // 30 分钟 }, }, }); function RootLayoutNav() { const { isAuthenticated, isLoading } = useAuth(); const { colorScheme } = useTheme(); if (isLoading) return null; return ( <> <StatusBar style={colorScheme === 'dark' ? 'light' : 'dark'} /> <Stack screenOptions={{ headerShown: false }}> {isAuthenticated ? ( <> <Stack.Screen name="(tabs)" /> <Stack.Screen name="(modals)" options={{ presentation: 'modal' }} /> </> ) : ( <Stack.Screen name="(auth)" /> )} <Stack.Screen name="+not-found" /> </Stack> </> ); } export default function RootLayout() { const [fontsLoaded] = useFonts({ // 自定义字体 }); useEffect(() => { if (fontsLoaded) { SplashScreen.hideAsync(); } }, [fontsLoaded]); if (!fontsLoaded) return null; return ( <QueryClientProvider client={queryClient}> <AuthProvider> <ThemeProvider> <RootLayoutNav /> </ThemeProvider> </AuthProvider> </QueryClientProvider> ); }

AI 生成的 Tab 布局代码:

// app/(tabs)/_layout.tsx import { Tabs } from 'expo-router'; import { Platform } from 'react-native'; import { Ionicons } from '@expo/vector-icons'; import { useThemeColor } from '@/hooks/useThemeColor'; export default function TabLayout() { const tabBarBg = useThemeColor('tabBar'); const activeColor = useThemeColor('primary'); const inactiveColor = useThemeColor('tabIconDefault'); return ( <Tabs screenOptions={{ tabBarActiveTintColor: activeColor, tabBarInactiveTintColor: inactiveColor, tabBarStyle: { backgroundColor: tabBarBg, borderTopWidth: 0, elevation: 0, shadowOpacity: 0, height: Platform.select({ ios: 88, android: 64 }), paddingBottom: Platform.select({ ios: 28, android: 8 }), }, headerShown: false, }} > <Tabs.Screen name="index" options={{ title: '首页', tabBarIcon: ({ color, size }) => ( <Ionicons name="home-outline" size={size} color={color} /> ), tabBarAccessibilityLabel: '首页', }} /> <Tabs.Screen name="discover" options={{ title: '发现', tabBarIcon: ({ color, size }) => ( <Ionicons name="compass-outline" size={size} color={color} /> ), tabBarAccessibilityLabel: '发现', }} /> <Tabs.Screen name="messages" options={{ title: '消息', tabBarIcon: ({ color, size }) => ( <Ionicons name="chatbubble-outline" size={size} color={color} /> ), tabBarBadge: 3, // 未读消息数 tabBarAccessibilityLabel: '消息,3 条未读', }} /> <Tabs.Screen name="profile" options={{ title: '我的', tabBarIcon: ({ color, size }) => ( <Ionicons name="person-outline" size={size} color={color} /> ), tabBarAccessibilityLabel: '我的', }} /> </Tabs> ); }

2.4.2 Deep Linking 配置

提示词模板:Deep Linking 配置

请为我的 Expo 应用配置 Deep Linking: ## URL Scheme - 自定义 scheme:myapp:// - Universal Links(iOS):https://myapp.com - App Links(Android):https://myapp.com ## 路由映射 - myapp://home → /(tabs)/index - myapp://item/[id] → /home/[id] - myapp://chat/[id] → /chat/[conversationId] - myapp://settings → /settings - myapp://share?content=[url] → /(modals)/share ## 要求 1. 配置 app.json 中的 scheme 和 intentFilters 2. 生成 apple-app-site-association 文件 3. 生成 assetlinks.json 文件 4. 处理未匹配路由的 fallback 5. 在应用冷启动和热启动时都能正确处理 Deep Link

2.4.3 认证流程导航

提示词模板:认证流程

请实现 Expo 应用的完整认证流程: ## 认证方式 1. 邮箱 + 密码登录 2. Apple Sign In(iOS) 3. Google Sign In(双平台) 4. 手机号 + 验证码(可选) ## 流程要求 - 使用 expo-auth-session 处理 OAuth - 使用 expo-apple-authentication 处理 Apple 登录 - Token 存储使用 expo-secure-store - 实现 Token 自动刷新机制 - 登录状态持久化(应用重启后保持登录) - 退出登录清除所有本地数据 ## 导航行为 - 未登录:显示 (auth) 路由组 - 已登录:显示 (tabs) 路由组 - Token 过期:自动刷新,刷新失败则跳转登录 - 首次安装:显示引导页(welcome),之后不再显示

2.5 状态管理:AI 辅助配置

Zustand(推荐用于 React Native)

提示词模板:Zustand Store 生成

请为 React Native + Expo 应用生成 Zustand 状态管理: ## Store 需求 1. AuthStore:用户认证状态 - user: User | null - token: string | null - isAuthenticated: boolean - login(credentials): Promise<void> - logout(): Promise<void> - refreshToken(): Promise<void> 2. CartStore:购物车状态 - items: CartItem[] - totalPrice: number(computed) - addItem(product, quantity): void - removeItem(itemId): void - updateQuantity(itemId, quantity): void - clearCart(): void ## 要求 - 使用 TypeScript 严格类型 - AuthStore 使用 expo-secure-store 持久化 token - CartStore 使用 zustand/middleware 的 persist + AsyncStorage - 包含 devtools 中间件(开发环境) - 每个 store 独立文件

AI 生成的 Zustand Store 示例:

// stores/authStore.ts import { create } from 'zustand'; import * as SecureStore from 'expo-secure-store'; interface User { id: string; name: string; email: string; avatar: string; } interface AuthState { user: User | null; token: string | null; isAuthenticated: boolean; isLoading: boolean; login: (email: string, password: string) => Promise<void>; logout: () => Promise<void>; refreshToken: () => Promise<void>; restoreSession: () => Promise<void>; } export const useAuthStore = create<AuthState>((set, get) => ({ user: null, token: null, isAuthenticated: false, isLoading: true, login: async (email, password) => { try { const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), }); if (!response.ok) throw new Error('登录失败'); const { user, token, refreshToken } = await response.json(); await SecureStore.setItemAsync('token', token); await SecureStore.setItemAsync('refreshToken', refreshToken); set({ user, token, isAuthenticated: true }); } catch (error) { throw error; } }, logout: async () => { await SecureStore.deleteItemAsync('token'); await SecureStore.deleteItemAsync('refreshToken'); set({ user: null, token: null, isAuthenticated: false }); }, refreshToken: async () => { try { const refreshToken = await SecureStore.getItemAsync('refreshToken'); if (!refreshToken) throw new Error('No refresh token'); const response = await fetch('/api/auth/refresh', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken }), }); if (!response.ok) throw new Error('Token 刷新失败'); const { token: newToken } = await response.json(); await SecureStore.setItemAsync('token', newToken); set({ token: newToken }); } catch { await get().logout(); } }, restoreSession: async () => { try { const token = await SecureStore.getItemAsync('token'); if (!token) { set({ isLoading: false }); return; } const response = await fetch('/api/auth/me', { headers: { Authorization: `Bearer ${token}` }, }); if (response.ok) { const user = await response.json(); set({ user, token, isAuthenticated: true, isLoading: false }); } else { await get().refreshToken(); set({ isLoading: false }); } } catch { set({ isLoading: false }); } }, }));

3. Flutter:AI 辅助开发深度指南

3.1 Flutter AI 开发生态现状(2025-2026)

Flutter 在 AI 辅助开发领域快速追赶 React Native,2025 年的关键进展包括:

  • Flutter 3.29-3.38:四个稳定版本发布,解决了 shader jank、Web 开发周期慢、Widget 预览等问题
  • FlutterFlow → Dreamflow:2025 年 7 月发布 Dreamflow,引入 AI-first 的三表面开发环境(Prompt + Visual + Code)
  • Riverpod 3.0:实验性支持离线持久化和 mutations,加上自动重试、泛型支持等改进
  • Cursor + Flutter 规则文件:社区成熟的 Flutter 规则文件让 AI 生成代码质量大幅提升
  • Google AI Dart SDK:官方 Dart SDK 支持 Gemini API 集成,Flutter 应用可直接调用 AI 能力

3.2 Flutter 开发环境配置

Cursor + Flutter 规则文件

Flutter 专用规则文件(.cursor/rules/flutter.mdc):

--- description: Flutter 开发规则 globs: ["**/*.dart", "lib/**/*"] --- # Flutter 开发规范 ## 技术栈 - Flutter 3.32+ / Dart 3.7+ - 状态管理:Riverpod 3.x(使用 riverpod_generator) - 路由:GoRouter 14.x - 网络:dio + retrofit - 本地存储:drift(SQLite)/ shared_preferences - 依赖注入:通过 Riverpod Provider ## Widget 规范 - 优先使用 StatelessWidget - 使用 const 构造函数优化重建 - Widget 拆分粒度:单个 Widget 不超过 80 行 - 使用 @riverpod 注解生成 Provider - 列表使用 ListView.builder / SliverList - 禁止在 build 方法中执行副作用 ## 文件结构 lib/ ├── app/ # 应用入口和路由 │ ├── app.dart │ └── router.dart ├── features/ # 按功能模块组织 │ └── [feature]/ │ ├── data/ # 数据层(Repository, DataSource) │ ├── domain/ # 领域层(Entity, UseCase) │ └── presentation/ # 展示层(Screen, Widget, Provider) ├── shared/ # 共享组件和工具 │ ├── widgets/ │ ├── theme/ │ └── utils/ └── main.dart ## 命名规范 - 文件名:snake_case(user_profile_screen.dart) - 类名:PascalCase(UserProfileScreen) - 变量/函数:camelCase(getUserProfile) - 常量:lowerCamelCase(defaultPadding) - Provider:camelCase + Provider 后缀(userProfileProvider) ## 主题规范 - 使用 ThemeData 统一管理 - 颜色使用 ColorScheme - 文字样式使用 TextTheme - 间距使用 EdgeInsets 常量 - 支持 Material Design 3 ## 平台适配 - 使用 Platform.isIOS / Platform.isAndroid 判断平台 - iOS 风格组件使用 Cupertino widgets - Android 风格组件使用 Material widgets - 使用 PlatformAdaptive 封装平台差异 ## 性能规范 - 使用 const Widget 减少重建 - 图片使用 cached_network_image - 避免在 build 中创建 Stream/Future - 使用 AutoDispose 自动释放资源 - 大列表使用 Sliver 系列 Widget

Claude Code + CLAUDE.md 配置

# CLAUDE.md(Flutter 项目) ## 项目概述 这是一个 Flutter 跨平台移动应用,支持 iOS 和 Android。 ## 技术栈 - Flutter 3.32+ / Dart 3.7+ - Riverpod 3.x(状态管理) - GoRouter 14.x(路由) - dio + retrofit(网络请求) - drift(本地数据库) - freezed(不可变数据类) ## 开发命令 - `flutter run`:运行应用 - `flutter test`:运行测试 - `dart run build_runner build`:代码生成 - `flutter analyze`:静态分析 - `flutter pub get`:安装依赖 ## 代码生成 本项目使用 build_runner 进行代码生成: - freezed:不可变数据类 - json_serializable:JSON 序列化 - riverpod_generator:Provider 生成 - retrofit_generator:API 客户端生成 修改带有 @freezed、@riverpod、@RestApi 注解的文件后, 必须运行 `dart run build_runner build --delete-conflicting-outputs` ## 架构规则 - 遵循 Clean Architecture(data → domain → presentation) - 每个 feature 独立目录 - Repository 模式隔离数据源 - UseCase 封装业务逻辑 - Provider 管理状态和依赖

3.3 AI 辅助 Widget 生成(Flutter)

3.3.1 基础 Widget 生成模式

提示词模板:Flutter Widget 生成

请为 Flutter 生成一个 [Widget 名称]: ## 功能需求 [详细描述 Widget 功能] ## 视觉规格 - 布局:[Row/Column/Stack 描述] - 使用 Material Design 3 组件 - 支持 Dark Mode(使用 Theme.of(context)) - 间距:使用 EdgeInsets 常量 ## 状态管理 - 使用 Riverpod(@riverpod 注解) - 状态类使用 freezed 不可变类 ## 平台适配 - iOS:使用 CupertinoNavigationBar / CupertinoButton - Android:使用 AppBar / ElevatedButton - 使用 Platform.isIOS 判断平台 ## 代码要求 - 使用 const 构造函数 - Widget 拆分粒度合理(每个 Widget < 80 行) - 包含完整的 Dart 类型注解 - 添加文档注释

示例:生成一个商品详情页 Widget

// lib/features/product/presentation/screens/product_detail_screen.dart import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'dart:io' show Platform; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:cached_network_image/cached_network_image.dart'; import '../providers/product_detail_provider.dart'; import '../widgets/product_image_carousel.dart'; import '../widgets/product_info_section.dart'; import '../widgets/add_to_cart_button.dart'; /// 商品详情页 /// /// 展示商品图片轮播、基本信息、规格选择和加入购物车功能。 /// 支持 iOS 和 Android 平台自适应导航栏。 class ProductDetailScreen extends ConsumerWidget { const ProductDetailScreen({ super.key, required this.productId, }); final String productId; @override Widget build(BuildContext context, WidgetRef ref) { final productAsync = ref.watch(productDetailProvider(productId)); return Scaffold( body: productAsync.when( data: (product) => _ProductDetailContent(product: product), loading: () => const _ProductDetailSkeleton(), error: (error, stack) => _ProductDetailError( error: error, onRetry: () => ref.invalidate(productDetailProvider(productId)), ), ), ); } } class _ProductDetailContent extends StatelessWidget { const _ProductDetailContent({required this.product}); final Product product; @override Widget build(BuildContext context) { return CustomScrollView( slivers: [ // 平台自适应导航栏 if (Platform.isIOS) CupertinoSliverNavigationBar( largeTitle: Text(product.name), trailing: CupertinoButton( padding: EdgeInsets.zero, child: const Icon(CupertinoIcons.share), onPressed: () => _shareProduct(context), ), ) else SliverAppBar( expandedHeight: 300, pinned: true, flexibleSpace: FlexibleSpaceBar( title: Text(product.name), ), actions: [ IconButton( icon: const Icon(Icons.share), onPressed: () => _shareProduct(context), ), ], ), // 图片轮播 SliverToBoxAdapter( child: ProductImageCarousel(images: product.images), ), // 商品信息 SliverToBoxAdapter( child: ProductInfoSection(product: product), ), // 底部间距 const SliverPadding(padding: EdgeInsets.only(bottom: 100)), ], ); } void _shareProduct(BuildContext context) { // 分享逻辑 } }

3.3.2 Riverpod 状态管理 AI 生成

提示词模板:Riverpod Provider 生成

请为 Flutter 应用生成 Riverpod 状态管理代码: ## Provider 需求 1. ProductListProvider:商品列表 - 支持分页加载(每页 20 条) - 支持下拉刷新 - 支持按分类筛选 - 使用 AsyncNotifier 2. CartProvider:购物车 - items: List<CartItem> - totalPrice: double(computed) - addItem / removeItem / updateQuantity - 持久化到本地存储 ## 要求 - 使用 @riverpod 注解(riverpod_generator) - 使用 freezed 定义不可变状态类 - 包含错误处理和重试逻辑 - 使用 AutoDispose 自动释放资源

AI 生成的 Riverpod Provider 示例:

// lib/features/product/domain/entities/product.dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'product.freezed.dart'; part 'product.g.dart'; @freezed class Product with _$Product { const factory Product({ required String id, required String name, required String description, required double price, required List<String> images, required String category, @Default(0) int stock, @Default(0.0) double rating, }) = _Product; factory Product.fromJson(Map<String, dynamic> json) => _$ProductFromJson(json); } // lib/features/product/presentation/providers/product_list_provider.dart import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../data/repositories/product_repository.dart'; import '../../domain/entities/product.dart'; part 'product_list_provider.g.dart'; @riverpod class ProductListNotifier extends _$ProductListNotifier { int _page = 1; bool _hasMore = true; String? _category; @override Future<List<Product>> build() async { _page = 1; _hasMore = true; return _fetchProducts(); } Future<List<Product>> _fetchProducts() async { final repository = ref.read(productRepositoryProvider); final products = await repository.getProducts( page: _page, pageSize: 20, category: _category, ); _hasMore = products.length == 20; return products; } Future<void> loadMore() async { if (!_hasMore) return; final currentProducts = state.valueOrNull ?? []; _page++; state = const AsyncValue.loading(); state = await AsyncValue.guard(() async { final newProducts = await _fetchProducts(); return [...currentProducts, ...newProducts]; }); } Future<void> refresh() async { _page = 1; _hasMore = true; ref.invalidateSelf(); } void filterByCategory(String? category) { _category = category; _page = 1; _hasMore = true; ref.invalidateSelf(); } }

3.4 GoRouter 导航配置(Flutter)

提示词模板:GoRouter 配置生成

请为 Flutter 应用配置 GoRouter 导航: ## 应用结构 - 启动页 → 引导页(首次安装)→ 登录/注册 - 主页面:底部导航栏(4 个 Tab) - Tab 1:首页(列表 → 详情) - Tab 2:分类(分类列表 → 商品列表 → 详情) - Tab 3:购物车 - Tab 4:我的(个人中心 → 设置 → 各设置项) - 全局路由:搜索、通知、图片预览 ## 要求 1. 使用 ShellRoute 实现底部导航栏持久化 2. 实现认证守卫(redirect) 3. 支持 Deep Linking 4. 使用 TypedGoRoute 类型安全路由 5. 路由过渡动画:iOS 使用 Cupertino 过渡,Android 使用 Material 过渡

AI 生成的 GoRouter 配置示例:

// lib/app/router.dart import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'dart:io' show Platform; import 'package:go_router/go_router.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../features/auth/presentation/providers/auth_provider.dart'; part 'router.g.dart'; @riverpod GoRouter router(Ref ref) { final authState = ref.watch(authProvider); return GoRouter( initialLocation: '/', debugLogDiagnostics: true, redirect: (context, state) { final isAuthenticated = authState.isAuthenticated; final isAuthRoute = state.matchedLocation.startsWith('/auth'); if (!isAuthenticated && !isAuthRoute) { return '/auth/login'; } if (isAuthenticated && isAuthRoute) { return '/'; } return null; }, routes: [ // 认证路由 GoRoute( path: '/auth/login', builder: (context, state) => const LoginScreen(), ), GoRoute( path: '/auth/register', builder: (context, state) => const RegisterScreen(), ), // 主页面(带底部导航栏) StatefulShellRoute.indexedStack( builder: (context, state, navigationShell) { return MainShell(navigationShell: navigationShell); }, branches: [ // Tab 1:首页 StatefulShellBranch( routes: [ GoRoute( path: '/', builder: (context, state) => const HomeScreen(), routes: [ GoRoute( path: 'product/:id', builder: (context, state) => ProductDetailScreen( productId: state.pathParameters['id']!, ), ), ], ), ], ), // Tab 2:分类 StatefulShellBranch( routes: [ GoRoute( path: '/categories', builder: (context, state) => const CategoriesScreen(), routes: [ GoRoute( path: ':categoryId', builder: (context, state) => CategoryProductsScreen( categoryId: state.pathParameters['categoryId']!, ), ), ], ), ], ), // Tab 3:购物车 StatefulShellBranch( routes: [ GoRoute( path: '/cart', builder: (context, state) => const CartScreen(), ), ], ), // Tab 4:我的 StatefulShellBranch( routes: [ GoRoute( path: '/profile', builder: (context, state) => const ProfileScreen(), routes: [ GoRoute( path: 'settings', builder: (context, state) => const SettingsScreen(), ), ], ), ], ), ], ), // 全局路由(不在底部导航栏内) GoRoute( path: '/search', pageBuilder: (context, state) => _buildPage( context, const SearchScreen(), ), ), ], ); } /// 平台自适应页面过渡 CustomTransitionPage<void> _buildPage( BuildContext context, Widget child, ) { return CustomTransitionPage( child: child, transitionsBuilder: (context, animation, secondaryAnimation, child) { if (Platform.isIOS) { return CupertinoPageTransition( primaryRouteAnimation: animation, secondaryRouteAnimation: secondaryAnimation, linearTransition: false, child: child, ); } return FadeTransition(opacity: animation, child: child); }, ); }

3.5 FlutterFlow / Dreamflow:可视化 + AI 构建

FlutterFlow 在 2025 年 7 月发布了 Dreamflow,引入了 AI-first 的三表面开发环境。

Dreamflow 三表面开发模式

┌──────────────────────────────────────────────────────────────┐ │ Dreamflow 三表面开发模式 │ ├──────────────────────────────────────────────────────────────┤ │ │ │ 表面 1:Prompt(AI 对话) │ │ ├─ 用自然语言描述需求 │ │ ├─ AI 自动生成 UI + 逻辑 + 主题 │ │ └─ 支持 Gemini、GPT-4、Claude 多模型 │ │ │ │ 表面 2:Visual(可视化编辑器) │ │ ├─ 拖拽式 UI 构建 │ │ ├─ 实时预览 │ │ └─ 属性面板精细调整 │ │ │ │ 表面 3:Code(代码编辑器) │ │ ├─ 直接编辑生成的 Flutter/Dart 代码 │ │ ├─ 自定义 Widget 和逻辑 │ │ └─ 代码变更实时同步到可视化编辑器 │ │ │ │ 三个表面保持同步,任何一个表面的修改都会反映到其他两个 │ │ │ └──────────────────────────────────────────────────────────────┘

FlutterFlow / Dreamflow 工具对比:

维度FlutterFlow(经典)Dreamflow(新版)
开发模式可视化优先AI + 可视化 + 代码三表面
AI 能力AI 辅助 UI 生成全面 AI 驱动(Prompt → 完整应用)
代码访问导出代码实时代码编辑 + 同步
AI Agent 构建有限支持无限 AI Agent(Pro/Team)
模型支持有限Gemini、GPT-4、Claude
价格免费 / $30/月 / $70/月包含在 FlutterFlow 订阅中
适用场景快速原型、MVP从原型到生产级应用

FlutterFlow AI 使用提示词:

在 FlutterFlow 中创建一个电商应用的商品详情页: 1. 顶部:商品图片轮播(支持缩放) 2. 中部:商品名称、价格、评分、描述 3. 规格选择:颜色和尺寸选择器 4. 底部固定栏:加入购物车 + 立即购买按钮 5. 使用 Material Design 3 主题 6. 支持 Dark Mode 7. 连接 Firebase Firestore 作为数据源

4. Expo 生态系统深度指南

4.1 Expo 托管工作流 vs 裸工作流

理解 Expo 的两种工作流对于 AI 辅助开发至关重要,因为它直接影响 AI 能生成什么样的代码。

维度托管工作流(Managed)裸工作流(Bare)
原生代码访问无(Expo 管理)完全访问 ios/ 和 android/ 目录
原生模块仅 Expo 模块 + Config Plugins任意原生模块
构建方式EAS Build(云端)本地 Xcode/Gradle 或 EAS Build
OTA 更新EAS Update(完整支持)EAS Update(需要配置)
AI 友好度★★★★★(AI 只需关注 JS/TS)★★★☆☆(AI 需要理解原生代码)
适用场景90% 的移动应用需要自定义原生模块的应用
迁移方向可随时 eject 到裸工作流无法回到托管工作流

AI 辅助决策:何时从托管切换到裸工作流

请评估我的 Expo 项目是否需要从托管工作流迁移到裸工作流: ## 当前使用的功能 [列出所有使用的 Expo 模块和第三方库] ## 需要但托管工作流不支持的功能 [列出需要原生代码访问的功能] ## 评估标准 1. 是否有 Expo Config Plugin 可以替代直接原生代码修改? 2. 是否有 Expo Module 可以替代第三方原生模块? 3. 迁移的工作量和维护成本是否值得? 4. 团队是否有 iOS/Android 原生开发经验? 请给出建议:继续使用托管工作流 / 迁移到裸工作流 / 使用 Config Plugin 解决

4.2 EAS Build:云端构建

EAS Build 是 Expo 的云端构建服务,让开发者无需本地配置 Xcode 或 Android Studio 即可构建原生二进制文件。

提示词模板:EAS Build 配置生成

请为我的 Expo 项目配置 EAS Build: ## 项目信息 - 应用名称:[名称] - Bundle ID(iOS):com.[company].[app] - Package Name(Android):com.[company].[app] - Expo SDK:54 ## 构建配置需求 1. development:开发构建(内部分发,包含 dev client) 2. preview:预览构建(内部测试,TestFlight / Internal Testing) 3. production:生产构建(App Store / Google Play 发布) ## 环境变量 - API_URL:不同环境不同值 - SENTRY_DSN:错误追踪 - ANALYTICS_KEY:数据分析 ## 要求 - 生成完整的 eas.json 配置 - 配置 app.config.ts(动态配置) - 配置 iOS 证书和 Android 签名 - 配置构建缓存优化构建速度

AI 生成的 eas.json 示例:

{ "cli": { "version": ">= 14.0.0", "appVersionSource": "remote" }, "build": { "development": { "developmentClient": true, "distribution": "internal", "ios": { "simulator": false, "resourceClass": "m-medium" }, "android": { "buildType": "apk" }, "env": { "API_URL": "https://dev-api.myapp.com", "APP_ENV": "development" }, "channel": "development" }, "preview": { "distribution": "internal", "ios": { "resourceClass": "m-medium" }, "android": { "buildType": "apk" }, "env": { "API_URL": "https://staging-api.myapp.com", "APP_ENV": "preview" }, "channel": "preview", "autoIncrement": true }, "production": { "ios": { "resourceClass": "m-medium" }, "android": { "buildType": "app-bundle" }, "env": { "API_URL": "https://api.myapp.com", "APP_ENV": "production" }, "channel": "production", "autoIncrement": true } }, "submit": { "production": { "ios": { "appleId": "[your-apple-id]", "ascAppId": "[your-asc-app-id]", "appleTeamId": "[your-team-id]" }, "android": { "serviceAccountKeyPath": "./google-services.json", "track": "internal" } } } }

4.3 EAS Update:OTA 热更新

EAS Update 是 Expo 的 OTA(Over-The-Air)更新服务,允许在不经过 App Store 审核的情况下推送 JavaScript 和资源更新。

提示词模板:EAS Update 配置

请为我的 Expo 应用配置 EAS Update 热更新策略: ## 更新策略 1. 关键 Bug 修复:立即强制更新 2. 功能更新:下次启动时更新 3. 内容更新:后台静默更新 ## 要求 - 配置 expo-updates 运行时版本策略 - 实现更新检查和下载逻辑 - 实现更新提示 UI(强制更新 / 可选更新) - 配置回滚机制(更新失败时回退到上一版本) - 集成到 CI/CD(GitHub Actions)

AI 生成的更新检查逻辑:

// hooks/useAppUpdate.ts import { useEffect, useState, useCallback } from 'react'; import * as Updates from 'expo-updates'; import { Alert, Platform } from 'react-native'; interface UpdateState { isChecking: boolean; isDownloading: boolean; isAvailable: boolean; progress: number; } export function useAppUpdate() { const [state, setState] = useState<UpdateState>({ isChecking: false, isDownloading: false, isAvailable: false, progress: 0, }); const checkForUpdate = useCallback(async () => { if (__DEV__) return; // 开发模式不检查更新 setState(prev => ({ ...prev, isChecking: true })); try { const update = await Updates.checkForUpdateAsync(); if (update.isAvailable) { setState(prev => ({ ...prev, isChecking: false, isAvailable: true, })); // 根据更新类型决定策略 const manifest = update.manifest; const isCritical = manifest?.extra?.expoClient?.extra?.critical; if (isCritical) { await forceUpdate(); } else { promptOptionalUpdate(); } } else { setState(prev => ({ ...prev, isChecking: false })); } } catch (error) { console.warn('更新检查失败:', error); setState(prev => ({ ...prev, isChecking: false })); } }, []); const forceUpdate = async () => { setState(prev => ({ ...prev, isDownloading: true })); try { const result = await Updates.fetchUpdateAsync(); if (result.isNew) { await Updates.reloadAsync(); } } catch (error) { console.error('更新下载失败:', error); setState(prev => ({ ...prev, isDownloading: false })); } }; const promptOptionalUpdate = () => { Alert.alert( '发现新版本', '有新的更新可用,是否立即更新?', [ { text: '稍后', style: 'cancel' }, { text: '更新', onPress: forceUpdate }, ] ); }; // 应用启动时检查更新 useEffect(() => { checkForUpdate(); }, [checkForUpdate]); return { ...state, checkForUpdate }; }

4.4 Expo Modules:自定义原生模块

当 Expo 内置模块无法满足需求时,可以使用 Expo Modules API 创建自定义原生模块。

提示词模板:Expo Module 生成

请使用 Expo Modules API 创建一个自定义原生模块: ## 模块功能 [描述需要的原生功能] ## 平台支持 - iOS:使用 Swift - Android:使用 Kotlin ## 要求 1. 使用 `npx create-expo-module` 创建模块骨架 2. 定义 TypeScript 接口 3. 实现 iOS Swift 代码 4. 实现 Android Kotlin 代码 5. 包含使用示例 6. 包含错误处理

5. 平台特定处理:AI 辅助策略

5.1 React Native 平台特定代码模式

React Native 提供了多种处理平台差异的方式,AI 需要根据场景选择最合适的模式。

模式一:Platform.select()

适用于简单的值差异(样式、配置等)。

import { Platform, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ container: { ...Platform.select({ ios: { shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, }, android: { elevation: 4, }, }), }, header: { paddingTop: Platform.select({ ios: 44, android: 0 }), height: Platform.select({ ios: 88, android: 56 }), }, });

模式二:Platform.OS 条件判断

适用于逻辑分支差异。

import { Platform } from 'react-native'; import * as Haptics from 'expo-haptics'; import { Vibration } from 'react-native'; function triggerHaptic() { if (Platform.OS === 'ios') { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); } else { Vibration.vibrate(50); } }

模式三:平台特定文件

适用于整个组件或模块的平台差异。

components/ ├── DatePicker.tsx # 共享接口定义 ├── DatePicker.ios.tsx # iOS 实现(使用 DateTimePicker) └── DatePicker.android.tsx # Android 实现(使用 Material DatePicker)
// DatePicker.ios.tsx import DateTimePicker from '@react-native-community/datetimepicker'; export function DatePicker({ value, onChange }: DatePickerProps) { return ( <DateTimePicker value={value} mode="date" display="spinner" // iOS 风格 onChange={(_, date) => date && onChange(date)} /> ); } // DatePicker.android.tsx import DateTimePicker from '@react-native-community/datetimepicker'; import { useState } from 'react'; import { Pressable, Text } from 'react-native'; export function DatePicker({ value, onChange }: DatePickerProps) { const [show, setShow] = useState(false); return ( <> <Pressable onPress={() => setShow(true)}> <Text>{value.toLocaleDateString()}</Text> </Pressable> {show && ( <DateTimePicker value={value} mode="date" display="default" // Android Material 风格 onChange={(_, date) => { setShow(false); date && onChange(date); }} /> )} </> ); }

提示词模板:平台特定组件生成

请为 React Native + Expo 生成一个平台自适应的 [组件名称]: ## 功能需求 [描述组件功能] ## 平台差异处理策略 请根据以下规则选择最合适的平台差异处理方式: 1. 仅样式差异 → 使用 Platform.select() 2. 简单逻辑分支 → 使用 Platform.OS 条件判断 3. 完全不同的实现 → 使用 .ios.tsx / .android.tsx 文件 ## iOS 特定要求 - 遵循 Human Interface Guidelines - 使用 SF Symbols 图标 - 使用 iOS 原生控件风格(如 ActionSheet、DatePicker) - 支持 Haptic Feedback ## Android 特定要求 - 遵循 Material Design 3 - 使用 Material Icons - 使用 Android 原生控件风格(如 BottomSheet、TimePicker) - 支持 Ripple 效果

5.2 Flutter 平台特定代码模式

Flutter 的平台适配主要通过 dart:ioPlatform 类和平台自适应 Widget 实现。

模式一:Platform 判断

import 'dart:io' show Platform; Widget buildNavBar(BuildContext context) { if (Platform.isIOS) { return CupertinoNavigationBar( middle: const Text('设置'), trailing: CupertinoButton( padding: EdgeInsets.zero, child: const Text('完成'), onPressed: () => Navigator.pop(context), ), ); } return AppBar( title: const Text('设置'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('完成'), ), ], ); }

模式二:平台自适应 Widget 封装

// lib/shared/widgets/adaptive_button.dart import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'dart:io' show Platform; /// 平台自适应按钮 /// /// iOS 上使用 CupertinoButton,Android 上使用 ElevatedButton class AdaptiveButton extends StatelessWidget { const AdaptiveButton({ super.key, required this.onPressed, required this.child, this.color, }); final VoidCallback? onPressed; final Widget child; final Color? color; @override Widget build(BuildContext context) { if (Platform.isIOS) { return CupertinoButton.filled( onPressed: onPressed, child: child, ); } return ElevatedButton( onPressed: onPressed, style: color != null ? ElevatedButton.styleFrom(backgroundColor: color) : null, child: child, ); } }

模式三:Platform Channel(原生通信)

当需要调用平台特定的原生 API 时,使用 Platform Channel。

// lib/services/native_share_service.dart import 'package:flutter/services.dart'; class NativeShareService { static const _channel = MethodChannel('com.myapp/share'); /// 调用原生分享功能 /// /// iOS 使用 UIActivityViewController /// Android 使用 Intent.ACTION_SEND static Future<bool> share({ required String text, String? url, String? imagePath, }) async { try { final result = await _channel.invokeMethod<bool>('share', { 'text': text, 'url': url, 'imagePath': imagePath, }); return result ?? false; } on PlatformException catch (e) { throw ShareException('分享失败: ${e.message}'); } } }

提示词模板:Flutter 平台适配

请为 Flutter 应用实现平台自适应的 [功能名称]: ## 功能需求 [描述功能] ## 平台差异 - iOS:[iOS 特定行为和 UI 风格] - Android:[Android 特定行为和 UI 风格] ## 实现策略 1. 创建平台自适应 Widget 封装 2. iOS 使用 Cupertino 系列 Widget 3. Android 使用 Material 系列 Widget 4. 共享业务逻辑,仅 UI 层做平台适配 5. 如需原生 API,使用 Platform Channel ## 代码要求 - 使用 Platform.isIOS / Platform.isAndroid 判断 - 封装为可复用的 Adaptive Widget - 包含完整的类型注解和文档注释

5.3 跨平台设计规范适配

AI 辅助设计规范检查提示词:

请审查以下跨平台移动应用代码,检查是否正确遵循了各平台的设计规范: ## 检查清单 ### iOS(Human Interface Guidelines) - [ ] 导航栏使用大标题(Large Title)模式 - [ ] 返回按钮显示上一页标题 - [ ] 使用 SF Symbols 图标 - [ ] 操作表使用 ActionSheet 而非 BottomSheet - [ ] 开关使用 Switch(iOS 风格) - [ ] 列表使用分组样式(Grouped) - [ ] 触觉反馈使用 Haptic Engine - [ ] 安全区域正确处理(刘海屏、Home Indicator) ### Android(Material Design 3) - [ ] 使用 Material You 动态颜色 - [ ] 导航栏使用 TopAppBar - [ ] 使用 Material Icons - [ ] 操作面板使用 BottomSheet - [ ] 开关使用 Material Switch - [ ] 列表使用 ListTile 样式 - [ ] 触觉反馈使用 Vibration API - [ ] 状态栏和导航栏颜色适配 ### 通用 - [ ] 最小触摸目标 44x44pt(iOS)/ 48x48dp(Android) - [ ] 支持 Dark Mode - [ ] 支持动态字体大小 - [ ] 无障碍标签完整 - [ ] 键盘避让正确 请列出所有不符合规范的地方,并提供修复代码。

6. AI 辅助跨平台组件生成进阶模式

6.1 设计到代码(Design-to-Code)

完整工作流:

┌──────────────────────────────────────────────────────────────┐ │ 设计到跨平台代码的 AI 工作流 │ ├──────────────────────────────────────────────────────────────┤ │ │ │ 输入方式(任选其一): │ │ ├─ A. Figma 设计稿 URL │ │ ├─ B. 设计截图(PNG/JPG) │ │ ├─ C. 手绘草图照片 │ │ └─ D. 自然语言描述 │ │ │ │ AI 处理流程: │ │ 1. 分析设计稿 → 识别组件层次结构 │ │ 2. 提取设计 Token → 颜色、字体、间距、圆角 │ │ 3. 映射到目标框架 → RN 组件 / Flutter Widget │ │ 4. 生成代码 → 包含样式、交互、无障碍 │ │ 5. 平台适配 → 处理 iOS/Android 差异 │ │ │ │ 输出: │ │ ├─ 组件代码文件 │ │ ├─ 主题/Token 文件 │ │ ├─ 使用示例 │ │ └─ 与设计稿的差异说明 │ │ │ └──────────────────────────────────────────────────────────────┘

提示词模板:截图到跨平台代码

请分析附带的移动端 UI 截图,生成 [React Native + Expo / Flutter] 代码: ## 分析要求 1. 识别所有 UI 元素和层次结构 2. 提取颜色值、字体大小、间距、圆角 3. 识别交互元素(按钮、输入框、开关等) 4. 识别列表/网格布局模式 ## 代码生成要求 1. 使用项目主题系统(不硬编码颜色值) 2. 组件拆分粒度合理(每个组件 < 100 行) 3. 包含完整的 TypeScript/Dart 类型 4. 添加无障碍标签 5. 支持 Dark Mode(推断暗色配色方案) 6. 处理 iOS/Android 平台差异 ## 输出格式 - 主组件文件 - 子组件文件(如果需要拆分) - 类型定义文件 - 使用示例

6.2 自然语言到复杂组件

提示词模板:复杂交互组件

请生成一个 [React Native / Flutter] 的可拖拽排序列表组件: ## 功能需求 - 长按列表项进入拖拽模式 - 拖拽时显示阴影和缩放动画 - 拖拽到目标位置时自动排序 - 支持左滑删除 - 支持右滑标记完成 - 拖拽结束后触发 haptic 反馈 ## 动画要求 - 使用 [react-native-reanimated / Flutter Animation] - 拖拽时 item 缩放 1.05x + 阴影加深 - 其他 item 平滑让位动画 - 删除动画:向左滑出 + 高度收缩 - 所有动画 60fps ## 性能要求 - 支持 100+ 条数据 - 动画在 UI 线程执行(不阻塞 JS 线程) - 使用 memo/const 优化重渲染 ## 无障碍要求 - VoiceOver/TalkBack 支持拖拽操作 - 提供替代的排序方式(上移/下移按钮)

6.3 组件库维护的 AI 工作流

提示词模板:组件库一致性检查

请审查我的跨平台组件库,检查一致性和质量: ## 检查维度 ### 1. API 一致性 - 所有组件的 Props/参数命名是否一致? - 回调函数命名是否统一(onPress vs onTap vs onClick)? - 尺寸参数是否使用统一的枚举(sm/md/lg)? ### 2. 主题一致性 - 所有组件是否使用主题系统的颜色? - 是否有硬编码的颜色值? - Dark Mode 是否完整支持? ### 3. 无障碍一致性 - 所有可交互组件是否有 accessibilityLabel? - 是否正确设置了 accessibilityRole? - 触摸目标是否满足最小尺寸要求? ### 4. 平台一致性 - iOS 和 Android 的行为差异是否正确处理? - 是否有遗漏的平台适配? ### 5. 性能一致性 - 是否所有纯展示组件都使用了 memo/const? - 是否有不必要的重渲染? 请列出所有问题,按严重程度排序,并提供修复建议。

7. 实战案例:用 AI 构建跨平台社交应用

案例背景

项目:一个图片社交应用(PhotoShare),支持 iOS 和 Android,核心功能包括图片发布、瀑布流浏览、点赞评论、用户关注。

技术选型:React Native + Expo SDK 54

AI 工具链:Bolt.new(原型)→ Cursor + 规则文件(开发)→ Claude Code(重构和测试)→ EAS Build(构建)→ EAS Update(热更新)

阶段 1:AI 快速原型(Bolt.new,30 分钟)

在 Bolt.new 中输入: 创建一个图片社交应用 PhotoShare,使用 React Native + Expo SDK 54: ## 核心页面 1. 首页(Feed):瀑布流图片列表,支持下拉刷新和无限滚动 2. 发布页:拍照/选择图片 → 添加滤镜 → 编辑描述 → 发布 3. 搜索页:搜索用户和标签,热门推荐 4. 通知页:点赞、评论、关注通知列表 5. 个人页:用户资料、图片网格、关注/粉丝数 ## 导航结构 - 底部 Tab:首页、搜索、发布(中间大按钮)、通知、我的 - 使用 expo-router ## 设计风格 - 简洁现代,类似 Instagram - 支持 Dark Mode - 主色调:渐变紫色(#667eea → #764ba2) ## 技术要求 - TypeScript 严格模式 - Zustand 状态管理 - expo-image 图片加载 - react-native-reanimated 动画

阶段 2:专业开发(Cursor,3-5 天)

将 Bolt.new 代码导入 Cursor,配置规则文件后进行专业化开发。

核心功能 AI 生成示例——瀑布流组件:

// components/feed/MasonryFeed.tsx import { memo, useCallback, useMemo } from 'react'; import { View, StyleSheet, RefreshControl, Dimensions } from 'react-native'; import { FlashList } from '@shopify/flash-list'; import { Image } from 'expo-image'; import Animated, { FadeInDown, useAnimatedStyle, withSpring, } from 'react-native-reanimated'; import { useRouter } from 'expo-router'; import { useThemeColor } from '@/hooks/useThemeColor'; const { width: SCREEN_WIDTH } = Dimensions.get('window'); const COLUMN_GAP = 8; const NUM_COLUMNS = 2; const ITEM_WIDTH = (SCREEN_WIDTH - COLUMN_GAP * 3) / NUM_COLUMNS; interface FeedItem { id: string; imageUrl: string; aspectRatio: number; user: { id: string; name: string; avatar: string; }; likesCount: number; isLiked: boolean; } interface MasonryFeedProps { items: FeedItem[]; isRefreshing: boolean; onRefresh: () => void; onLoadMore: () => void; onLike: (itemId: string) => void; } function MasonryFeed({ items, isRefreshing, onRefresh, onLoadMore, onLike, }: MasonryFeedProps) { const router = useRouter(); const bgColor = useThemeColor('background'); const renderItem = useCallback( ({ item, index }: { item: FeedItem; index: number }) => ( <Animated.View entering={FadeInDown.delay(index * 50).springify()}> <FeedCard item={item} onPress={() => router.push(`/post/${item.id}`)} onLike={() => onLike(item.id)} /> </Animated.View> ), [router, onLike] ); return ( <FlashList data={items} renderItem={renderItem} estimatedItemSize={200} numColumns={NUM_COLUMNS} keyExtractor={(item) => item.id} onEndReached={onLoadMore} onEndReachedThreshold={0.5} refreshControl={ <RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} tintColor={useThemeColor('primary')} /> } contentContainerStyle={styles.listContent} ItemSeparatorComponent={() => <View style={styles.separator} />} /> ); } export default memo(MasonryFeed); // 子组件:单个卡片 const FeedCard = memo(function FeedCard({ item, onPress, onLike, }: { item: FeedItem; onPress: () => void; onLike: () => void; }) { const cardBg = useThemeColor('card'); const textColor = useThemeColor('text'); const imageHeight = ITEM_WIDTH / item.aspectRatio; return ( <Pressable onPress={onPress} style={[styles.card, { backgroundColor: cardBg }]} accessibilityLabel={`${item.user.name} 发布的图片`} accessibilityRole="button" > <Image source={{ uri: item.imageUrl }} style={[styles.image, { height: imageHeight }]} contentFit="cover" transition={300} placeholder="L6PZfSi_.AyE_3t7t7R**0o#DgR4" /> <View style={styles.cardFooter}> <Image source={{ uri: item.user.avatar }} style={styles.avatar} contentFit="cover" /> <Text style={[styles.userName, { color: textColor }]} numberOfLines={1} > {item.user.name} </Text> <Pressable onPress={onLike} hitSlop={8} accessibilityLabel={ item.isLiked ? '取消点赞' : '点赞' } > <Ionicons name={item.isLiked ? 'heart' : 'heart-outline'} size={18} color={item.isLiked ? '#ff4757' : textColor} /> </Pressable> </View> </Pressable> ); }); const styles = StyleSheet.create({ listContent: { padding: COLUMN_GAP, }, separator: { height: COLUMN_GAP, }, card: { borderRadius: 12, overflow: 'hidden', marginHorizontal: COLUMN_GAP / 2, }, image: { width: '100%', }, cardFooter: { flexDirection: 'row', alignItems: 'center', padding: 8, }, avatar: { width: 24, height: 24, borderRadius: 12, }, userName: { flex: 1, fontSize: 12, marginLeft: 6, }, });

阶段 3:AI 辅助重构与测试(Claude Code,1-2 天)

使用 Claude Code 进行代码质量提升和测试生成:

# 在项目根目录启动 Claude Code claude # 提示词:代码审查与重构 请审查整个项目代码,重点关注: 1. TypeScript 类型安全性(消除所有 any 类型) 2. 性能优化(memo、useCallback、useMemo 使用是否合理) 3. 无障碍合规性(所有可交互元素是否有标签) 4. 平台差异处理(是否有遗漏的 iOS/Android 差异) 5. 错误处理(网络错误、权限拒绝等边界情况) 请逐个文件审查,列出问题并直接修复。
# 提示词:生成测试 请为 PhotoShare 应用生成完整的测试套件: 1. 单元测试(Jest): - Zustand stores 的所有 action - 工具函数(图片压缩、格式化等) - 自定义 hooks 2. 组件测试(React Native Testing Library): - FeedCard 渲染和交互 - UserProfileCard 渲染和交互 - 表单组件验证逻辑 3. E2E 测试(Maestro): - 用户注册 登录流程 - 发布图片流程 - 浏览 Feed 点赞 评论流程 - 搜索用户 关注流程

阶段 4:构建与发布(EAS,半天)

# 使用 Claude Code 配置 EAS 请帮我配置 PhotoShare EAS 构建和发布流程: 1. 配置 eas.json(development / preview / production) 2. 配置 app.config.ts(动态配置,区分环境) 3. 配置 GitHub Actions CI/CD: - PR 合并到 main 自动构建 preview 版本 - tag 自动构建 production 版本并提交到 App Store / Google Play 4. 配置 EAS Update: - 热修复分支 自动推送 OTA 更新 5. 配置 Sentry 错误追踪集成

案例分析

关键决策点:

  1. 技术选型:选择 React Native + Expo 而非 Flutter,因为图片社交应用的 AI 辅助开发在 RN 生态中更成熟(Bolt.new 支持、Claude Code Skills 丰富)
  2. 状态管理:选择 Zustand 而非 Redux,因为 AI 生成 Zustand 代码更简洁,样板代码更少
  3. 图片加载:选择 expo-image 而非 react-native-fast-image,因为 expo-image 是 Expo 官方维护,与托管工作流兼容性更好
  4. 列表性能:选择 FlashList 而非 FlatList,因为 FlashList 在大数据量下性能显著更好
  5. 动画:选择 react-native-reanimated 而非 Animated API,因为 reanimated 在 UI 线程执行动画,不阻塞 JS 线程

AI 工具使用时间分配:

阶段工具时间产出
原型Bolt.new30 分钟可运行的基础应用
开发Cursor + 规则文件3-5 天完整功能实现
重构Claude Code1 天代码质量提升
测试Claude Code + Maestro1 天测试套件
发布Claude Code + EAS半天CI/CD + 构建配置
总计约 6-8 天生产级跨平台应用

对比传统开发:同等功能的应用,传统开发通常需要 4-6 周(1-2 名开发者)。AI 辅助开发将时间缩短到约 1 周,效率提升 4-6 倍。


8. 跨平台开发 Prompt 模板集

8.1 项目初始化模板

请初始化一个 [React Native + Expo / Flutter] 跨平台移动应用项目: ## 项目信息 - 应用名称:[名称] - 应用描述:[一句话描述] - 目标平台:iOS 17+ / Android 14+(API 34+) ## 技术栈 - 框架:[React Native + Expo SDK 54 / Flutter 3.32+] - 语言:[TypeScript / Dart] - 状态管理:[Zustand / Riverpod] - 路由:[expo-router / GoRouter] - 网络:[@tanstack/react-query / dio + retrofit] - 本地存储:[AsyncStorage + SecureStore / drift + shared_preferences] ## 项目结构 请生成完整的项目目录结构和基础配置文件。 ## 基础功能 1. 主题系统(Light/Dark Mode) 2. 导航结构([描述 Tab 和 Stack 结构]) 3. 认证流程骨架 4. API 服务层骨架 5. 错误处理和 Loading 状态管理

8.2 功能模块生成模板

请为 [React Native / Flutter] 应用生成 [功能模块名称] 模块: ## 模块功能 [详细描述模块功能] ## 页面列表 1. [页面 1]:[描述] 2. [页面 2]:[描述] 3. [页面 3]:[描述] ## 数据模型 [描述数据结构] ## API 接口 - GET /api/[resource]:[描述] - POST /api/[resource]:[描述] - PUT /api/[resource]/:id:[描述] - DELETE /api/[resource]/:id:[描述] ## 状态管理 [描述需要管理的状态] ## 要求 - 完整的 TypeScript/Dart 类型定义 - 错误处理和 Loading 状态 - 离线缓存策略 - 平台差异处理 - 无障碍支持 - 单元测试

8.3 性能优化模板

请优化我的 [React Native / Flutter] 应用的性能: ## 当前问题 [描述性能问题:卡顿、内存泄漏、启动慢等] ## 优化范围 1. 启动性能 - 减少启动时间 - 优化 splash screen 过渡 - 延迟加载非关键模块 2. 渲染性能 - 减少不必要的重渲染 - 优化长列表滚动 - 优化动画帧率 3. 内存优化 - 图片缓存策略 - 组件卸载时清理资源 - 避免内存泄漏 4. 网络优化 - 请求合并和缓存 - 图片压缩和格式优化 - 离线优先策略 5. 包体积优化 - 移除未使用的依赖 - 代码分割 - 资源压缩 ## 要求 - 每项优化提供具体的代码修改 - 说明预期的性能提升 - 提供性能测量方法

8.4 App Store 提交模板

请帮我准备 [iOS App Store / Google Play] 提交所需的所有材料: ## 应用信息 - 应用名称:[名称] - 副标题:[副标题] - 分类:[主分类] / [副分类] - 年龄分级:[4+ / 9+ / 12+ / 17+] ## 需要生成的内容 1. 应用描述(中文 + 英文,4000 字符以内) 2. 关键词(100 字符以内,逗号分隔) 3. 更新说明(What's New) 4. 隐私政策 URL 内容 5. 截图文案(每张截图的标题和副标题) 6. 审核备注(如有特殊功能需要说明) ## 隐私相关 - 收集的数据类型:[列出] - 数据用途:[列出] - 第三方 SDK:[列出] - 是否有账号系统:[是/否] - 是否有应用内购买:[是/否]

避坑指南

❌ 常见错误

  1. AI 生成的代码不处理平台差异

    • 问题:AI 默认生成的代码可能只在一个平台上测试过,另一个平台出现布局错乱或功能异常
    • 正确做法:在 Steering 规则中明确要求处理平台差异,每次生成代码后在 iOS 和 Android 上都测试
  2. 过度依赖 Bolt.new 生成的代码

    • 问题:Bolt.new 生成的代码适合原型,但缺少性能优化、错误处理、类型安全等生产级要求
    • 正确做法:将 Bolt.new 作为起点(60-70%),在专业 IDE 中用 AI 辅助完善剩余部分
  3. 忽略 Expo SDK 版本兼容性

    • 问题:AI 可能生成基于旧版 SDK 的代码,导致 API 不兼容或弃用警告
    • 正确做法:在 Steering 规则中明确指定 Expo SDK 版本,使用 Claude Code 的 react-native-expo Skill 确保版本兼容
  4. Flutter 中忘记运行代码生成

    • 问题:修改了 @freezed@riverpod@RestApi 注解的文件后,忘记运行 build_runner,导致编译错误
    • 正确做法:在 CLAUDE.md 中明确说明代码生成命令,或配置 build_runner watch 自动生成
  5. 导航配置混乱

    • 问题:AI 生成的导航配置可能混淆 expo-router 的文件系统路由和手动配置的 React Navigation
    • 正确做法:在规则文件中明确指定使用 expo-router,禁止混用两种导航方案
  6. 状态管理过度设计

    • 问题:AI 可能为简单的本地状态也创建全局 Store,导致不必要的复杂性
    • 正确做法:在 Steering 规则中明确状态管理策略——组件本地状态用 useState,跨组件共享状态用 Zustand/Riverpod,服务端状态用 react-query/Riverpod AsyncNotifier
  7. 忽略移动端性能约束

    • 问题:AI 生成的代码可能在模拟器上运行流畅,但在低端真机上卡顿(如使用 ScrollView + map 渲染长列表)
    • 正确做法:在规则文件中强制使用虚拟化列表(FlashList/FlatList/ListView.builder),禁止在 ScrollView 中渲染大量子元素
  8. EAS Build 配置不区分环境

    • 问题:开发、预览、生产环境使用相同的 API 地址和配置
    • 正确做法:在 eas.json 中为每个 profile 配置不同的环境变量,使用 app.config.ts 动态读取

✅ 最佳实践

  1. 先写 Steering 规则,再开始开发:在项目开始前,花 15 分钟编写移动端专用的 Steering 规则文件,明确技术栈、代码规范、平台适配策略,这会让后续所有 AI 生成的代码质量大幅提升

  2. 使用 Expo Go 缩短反馈循环:开发过程中保持 Expo Go 实时预览,AI 生成代码后立即在真机上验证,发现问题及时修正

  3. 组件先生成、后优化:让 AI 先生成功能完整的组件,然后再用 AI 进行性能优化(添加 memo、优化重渲染、处理边界情况)

  4. 利用 Claude Code Skills:安装社区维护的 React Native + Expo Skills(如 react-native-expo skill),它们包含了版本特定的最佳实践和已知问题规避

  5. 每个功能模块独立生成和测试:不要一次性让 AI 生成整个应用,而是按功能模块逐个生成、测试、集成,这样更容易发现和修复问题

  6. 保持 TypeScript/Dart 严格模式:在 Steering 规则中强制 TypeScript strict 模式或 Dart 严格类型检查,AI 生成的代码类型安全性会显著提升

  7. 定期运行平台双端测试:每完成一个功能模块,在 iOS 和 Android 上都运行一遍,不要等到最后才发现平台差异问题


相关资源与延伸阅读

  1. Expo 官方文档 :Expo SDK、expo-router、EAS Build/Update 的权威参考
  2. React Native 官方文档 :React Native 核心 API 和平台特定代码指南
  3. Flutter 官方文档 :Flutter Widget 目录、状态管理、平台集成指南
  4. Riverpod 官方文档 :Riverpod 3.x 状态管理完整指南
  5. GoRouter 文档 :Flutter GoRouter 路由配置和 Deep Linking
  6. FlutterFlow / Dreamflow :可视化 + AI 辅助的 Flutter 应用构建平台
  7. Bolt.new :AI 驱动的移动应用生成器,支持 Expo 集成
  8. Claude Code React Native Expo Agent System :7 个生产级 Agent 的 React Native/Expo 开发工具包
  9. awesome-cursorrules - Flutter :社区维护的 Flutter 和 React Native Cursor 规则文件集合
  10. Maestro 移动端测试框架 :声明式移动端 E2E 测试,AI 生成友好

参考来源


📖 返回 总览与导航 | 上一节:33a-AI辅助移动端开发概览 | 下一节:33c-原生模块开发

Last updated on