前言

本文为纯原创实战教程,基于 HarmonyOS Next + ArkTS + Stage 模型,从零实现一个可直接运行的任务管理 App,包含:

  • 环境搭建
  • 项目结构
  • UI 组件开发
  • 状态管理
  • 本地数据持久化
  • 跨端适配
  • 性能优化
  • 调试与发布

在这里插入图片描述

一、HarmonyOS 开发环境准备

1.1 开发工具

  • DevEco Studio(官方推荐,最新版)
  • JDK:内置,无需额外安装
  • HarmonyOS SDK:安装时自动下载

1.2 开发环境配置

  1. 安装 DevEco Studio
  2. 配置 SDK 路径
  3. 安装模拟器或连接真机
  4. 注册华为开发者账号(发布需要)

二、创建项目与目录结构

2.1 新建项目

  1. 打开 DevEco Studio → Create Project
  2. 选择 Empty Ability
  3. 配置:
    • 名称:TaskManager
    • 包名:com.example.taskmanager
    • 语言:ArkTS
    • 模型:Stage 模型

2.2 核心目录说明

entry/src/main/ets/
├── component/ # 自定义组件
├── model/ # 数据模型
├── utils/ # 工具类
└── pages/ # 页面

2.3 module.json5 配置

{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "$string:module_desc",
    "mainElement": "EntryAbility",
    "deviceTypes": [
      "phone",
      "tablet"
    ],
    "deliveryWithInstall": true,
    "installationFree": false
  }
}

三、任务管理 App 核心代码实现

3.1 定义任务数据模型

model/Task.ets

export interface Task {
  id: number;
  content: string;
  isCompleted: boolean;
  createTime: number;
}

3.2 列表项组件

component/TaskItem.ets

@Component
export struct TaskItem {
  @Prop task: Task;
  @Event onToggle: (id: number) => void;
  @Event onDelete: (id: number) => void;

  build() {
    Row() {
      Checkbox()
        .select(this.task.isCompleted)
        .onChange(() => this.onToggle(this.task.id))

      Text(this.task.content)
        .fontSize(16)
        .fontColor(this.task.isCompleted ? '#999' : '#333')
        .decoration(this.task.isCompleted ? TextDecoration.LineThrough : TextDecoration.None)

      Blank()

      Button("删除")
        .backgroundColor(Color.Red)
        .fontColor(Color.White)
        .onClick(() => this.onDelete(this.task.id))
    }
    .padding(12)
    .backgroundColor("#f5f5f5")
    .borderRadius(8)
    .margin({ bottom: 8 })
  }
}

3.3 主页面逻辑 + UI

pages/Index.ets

import { Task } from '../model/Task';
import { TaskItem } from '../component/TaskItem';

@Entry
@Component
struct Index {
  @State tasks: Task[] = [];
  @State newTaskContent: string = '';

  // 切换完成状态
  private toggleTask(id: number) {
    this.tasks = this.tasks.map(t => {
      if (t.id === id) {
        return { ...t, isCompleted: !t.isCompleted };
      }
      return t;
    });
  }

  // 删除任务
  private deleteTask(id: number) {
    this.tasks = this.tasks.filter(t => t.id !== id);
  }

  // 添加任务
  private addTask() {
    if (this.newTaskContent.trim() === '') return;
    const newTask: Task = {
      id: Date.now(),
      content: this.newTaskContent,
      isCompleted: false,
      createTime: Date.now()
    };
    this.tasks = [newTask, ...this.tasks];
    this.newTaskContent = '';
  }

  build() {
    Column() {
      // 输入栏
      Row() {
        TextInput({ placeholder: '输入任务内容' })
          .height(40)
          .layoutWeight(1)
          .onChange(v => this.newTaskContent = v)

        Button('添加')
          .backgroundColor('#007DFF')
          .onClick(() => this.addTask())
      }
      .padding(12)

      // 列表
      List() {
        ForEach(this.tasks, (task: Task) => {
          ListItem() {
            TaskItem({
              task: task,
              onToggle: (id) => this.toggleTask(id),
              onDelete: (id) => this.deleteTask(id)
            })
          }
        })
      }
      .layoutWeight(1)
      .padding(12)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#fff')
  }
}

3.4 本地数据持久化(Preferences)

utils/TaskStorage.ets

import preferences from '@ohos.data.preferences';
import { Task } from '../model/Task';

const NAME = 'task_db';
const KEY = 'task_list';

export class TaskStorage {
  private static ins: preferences.Preferences | null = null;

  static async init(ctx: Context) {
    if (!this.ins) {
      this.ins = await preferences.getPreferences(ctx, NAME);
    }
  }

  static async save(tasks: Task[]) {
    await this.ins?.put(KEY, JSON.stringify(tasks));
    await this.ins?.flush();
  }

  static async load(): Promise<Task[]> {
    const str = await this.ins?.get(KEY, '[]') as string;
    return JSON.parse(str) || [];
  }
}

在 Index.ets 中加入生命周期:

async aboutToAppear() {
  await TaskStorage.init(getContext(this) as Context);
  this.tasks = await TaskStorage.load();
}

async aboutToDisappear() {
  await TaskStorage.save(this.tasks);
}

四、跨端适配与性能优化

4.1 响应式布局

使用 GridRow / GridCol 实现多端自适应:

GridRow({ gutter: 12 }) {
  GridCol({ span: { sm:12, md:8, lg:6 } }) {
    // 内容
  }
}

4.2 性能优化要点

  1. 长列表使用 LazyForEach
  2. 合理拆分小组件,减少重绘
  3. 避免在 build 中做复杂计算
  4. 图片使用 WebP 格式

五、调试、运行与发布

5.1 运行项目

  1. 启动模拟器 / 连接真机
  2. 点击运行按钮
  3. 查看日志:HiLog / 控制台

5.2 打包发布

  1. 生成签名证书
  2. Build Hap / App
  3. 上传华为应用市场

六、总结

本文完整实现了:

  • HarmonyOS 项目搭建
  • ArkTS 组件与状态管理
  • 任务增删改查
  • 本地数据持久化
  • 跨端适配与优化思路
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐