Chuyển đến nội dung chính

第 16 課:移動和跨平台 Vibe 編碼

使用 Vibe Coding 開發行動應用程式。 React Native 和 Flutter 工作流程。 UI 產生、導航、API 整合。特定於平台的程式碼。測試行動應用程式。部署到 App Store 和 Google Play。

💻 程式設計 — 第 16 課 第 16 課:行動裝置和裝置的 Vibe 編碼 跨平台

使用 GitHub Copilot 進行 Vibe 編碼:從基礎知識到高級

第 5 部分:Vibe 編碼實踐 — 建構真實項目

亞洲開發網

1. 行動裝置上的 Vibe 編碼 — 它與 Web 有何不同?

行動開發有其自身的特點,Vibe Coding需要適應:

特點 網路 智慧型手機
佈局 CSS 彈性盒/網格 特定於平台的佈局
導航 基於 URL 的路由 堆疊/選項卡導航
測試 瀏覽器→即時回饋 模擬器/設備→較慢
原生 API 限制 相機、GPS、感光元件、推播
效能 DOM渲染 原生渲染
部署 Vercel/Netlify 應用商店審核流程

2. 使用 Vibe 編碼回應 Native

2.1.設定項目

// Prompt:
Create a React Native project with Expo for the Task Management app.
Include:
- TypeScript
- React Navigation (stack + bottom tabs)
- React Query for API calls
- AsyncStorage for local state
- Expo secure-store for auth tokens
- NativeWind (TailwindCSS for React Native)

2.2.與後端共享類型

// Prompt:
I have a backend with these API responses (paste TypeScript types).
Generate React Native API client and hooks that match these types exactly.
Reuse the same Zod schemas from the web frontend.
// src/hooks/useTasks.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../lib/api';
import type { Task, CreateTaskInput } from '../types';

export function useTasks(projectId: string) {
  return useQuery({
    queryKey: ['tasks', projectId],
    queryFn: () => api.get<Task[]>(`/tasks?projectId=${projectId}`),
  });
}

export function useCreateTask() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreateTaskInput) => api.post('/tasks', data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: ['tasks', variables.projectId],
      });
    },
  });
}

2.3.行動專用 UI

// Prompt:
Create a task list screen for React Native with:
- Pull to refresh
- Infinite scroll pagination
- Swipe to complete/delete
- FAB (floating action button) to add tasks
- Priority color indicators
- Use NativeWind for styling
// src/screens/TaskListScreen.tsx
import { FlatList, RefreshControl, View, Text, Pressable } from 'react-native';
import { Swipeable } from 'react-native-gesture-handler';
import { useTasks } from '../hooks/useTasks';

export function TaskListScreen({ route }) {
  const { projectId } = route.params;
  const { data, isLoading, refetch } = useTasks(projectId);

  const priorityColors = {
    LOW: 'bg-green-500',
    MEDIUM: 'bg-yellow-500',
    HIGH: 'bg-orange-500',
    URGENT: 'bg-red-500',
  };

  const renderTask = ({ item: task }) => (
    <Swipeable
      renderRightActions={() => (
        <Pressable className="bg-green-500 justify-center px-6"
          onPress={() => completeTask(task.id)}>
          <Text className="text-white font-bold">Done</Text>
        </Pressable>
      )}>
      <View className="bg-white p-4 border-b border-gray-100 flex-row items-center">
        <View className={`w-3 h-3 rounded-full mr-3 ${priorityColors[task.priority]}`} />
        <View className="flex-1">
          <Text className="font-semibold text-gray-900">{task.title}</Text>
          <Text className="text-gray-500 text-sm">{task.assignee?.name}</Text>
        </View>
      </View>
    </Swipeable>
  );

  return (
    <View className="flex-1 bg-gray-50">
      <FlatList
        data={data}
        renderItem={renderTask}
        refreshControl={
          <RefreshControl refreshing={isLoading} onRefresh={refetch} />
        }
      />
    </View>
  );
}

3. 使用 Vibe 編碼進行 Flutter

3.1.顫動項目設置

// Prompt:
Create a Flutter app for Task Management with:
- Clean architecture (presentation, domain, data layers)
- Riverpod for state management
- Go Router for navigation
- Dio for API calls
- Freezed for immutable models
- Material 3 design

3.2. Dart模型生成

// Prompt:
Generate Freezed models for these API responses:
- Task (id, title, description, status, priority, dueDate, assignee)
- Project (id, name, description, owner)
- User (id, email, name, avatar)
Include fromJson/toJson serialization.
// lib/models/task.dart
import 'package:freezed_annotation/freezed_annotation.dart';

part 'task.freezed.dart';
part 'task.g.dart';

@freezed
class Task with _$Task {
  const factory Task({
    required String id,
    required String title,
    String? description,
    @Default(TaskStatus.todo) TaskStatus status,
    @Default(Priority.medium) Priority priority,
    DateTime? dueDate,
    User? assignee,
  }) = _Task;

  factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
}

enum TaskStatus {
  @JsonValue('TODO') todo,
  @JsonValue('IN_PROGRESS') inProgress,
  @JsonValue('IN_REVIEW') inReview,
  @JsonValue('DONE') done,
}

enum Priority {
  @JsonValue('LOW') low,
  @JsonValue('MEDIUM') medium,
  @JsonValue('HIGH') high,
  @JsonValue('URGENT') urgent,
}

3.3. Flutter UI 與 Copilot

// Prompt:
Create a Flutter task board widget with:
- Horizontal scrollable columns (Todo, In Progress, Done)
- Draggable task cards between columns
- Material 3 card design
- Pull to refresh
- Hero animation when opening task detail

4. 特定於平台的程式碼

// Prompt:
Add push notifications to the mobile app:
- Firebase Cloud Messaging setup
- Handle foreground/background/terminated states  
- Deep link to specific task when notification tapped
- Platform-specific code for iOS (APNs) and Android (FCM)

副駕駛明白 平台差異 並為每個平台產生適當的程式碼。

5. 比較:React Native 與 Flutter 的 Vibe 編碼

標準 反應本機 顫動
人工智慧程式碼品質 好(大量訓練資料) 良好(不斷發展的生態系統)
與網路共享程式碼 高(共享 TypeScript) 低(私人飛鏢)
副駕駛建議 非常準確(JS/TS) 精準(飛鏢)
組件生成 快速(熟悉 JSX) 快速(小部件樹)
使用人工智慧進行測試 開玩笑 + RTL(熟悉) 小部件測試(學習曲線)
熱重載 快速刷新✅ 熱重載 ✅

推薦:如果團隊使用了 React for web → React Native。如果您需要高效能和自訂 UI → Flutter。

6. 測試行動應用程式

// Prompt cho React Native:
Write tests for TaskListScreen:
- Renders task list from API
- Pull to refresh calls refetch
- Swipe right completes task
- Shows loading indicator
- Shows empty state when no tasks
Use @testing-library/react-native
// Prompt cho Flutter:
Write widget tests for TaskBoard:
- Renders columns with correct titles
- Shows tasks in correct columns
- Drag and drop changes task status
- Pull to refresh triggers reload

7. 部署行動應用程式

// Prompt:
Create a CI/CD pipeline for the React Native app:
- GitHub Actions workflow
- Build for iOS (using Expo EAS)
- Build for Android (using Expo EAS)
- Auto-submit to TestFlight and Google Play Internal Testing
- Run tests before build

八、總結

移動任務 Vibe 編碼效率
使用者介面螢幕 ⭐⭐⭐⭐⭐ 非常有效
API集成 ⭐⭐⭐⭐⭐ 模式種安全且快速
導航 ⭐⭐⭐⭐ 擅長熟悉的模式
原生 API ⭐⭐⭐ 需要查看平台細節
效能調優 ⭐⭐ 需要人類專業知識
應用程式商店提交 ⭐⭐⭐ CI/CD 設定良好,但需要手動審核

第 6 部分將重點關注 品質與專業 — 程式碼品質、安全性、技術債以及與 Vibe Coding 的團隊合作。