diff --git a/ohos/asynchronous/.gitignore b/ohos/asynchronous/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..24476c5d1eb55824c76d8b01a3965f94abad1ef8 --- /dev/null +++ b/ohos/asynchronous/.gitignore @@ -0,0 +1,44 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/ohos/asynchronous/README.md b/ohos/asynchronous/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ohos/asynchronous/analysis_options.yaml b/ohos/asynchronous/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61b6c4de17c96863d24279f06b85e01b6ebbdb34 --- /dev/null +++ b/ohos/asynchronous/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/ohos/asynchronous/lib/async_await.dart b/ohos/asynchronous/lib/async_await.dart new file mode 100644 index 0000000000000000000000000000000000000000..a9ff46c04973919f649d33c03e611cd5cbf92581 --- /dev/null +++ b/ohos/asynchronous/lib/async_await.dart @@ -0,0 +1,110 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'package:flutter/material.dart'; + +class AsyncAwaitExample extends StatefulWidget { + const AsyncAwaitExample({Key? key}) : super(key: key); + + @override + _AsyncAwaitExampleState createState() => _AsyncAwaitExampleState(); +} + +class _AsyncAwaitExampleState extends State { + List _students = []; // 存储学生信息的列表 + + @override + void initState() { + super.initState(); + // 调用异步函数并更新 UI + fetchStudentsData(); + } + + // 模拟一个异步网络请求,返回学生数据(30个学生) + Future> fetchStudentsFromNetwork() async { + await Future.delayed(const Duration(seconds: 2)); // 模拟网络延迟 + + // 模拟返回的学生信息(30个学生) + List> studentsJson = List.generate(30, (index) { + return { + 'name': 'Student ${index + 1}', + 'age': 18 + (index % 5), // 随机年龄范围:18-22 + 'grade': 'Grade ${['A', 'B', 'C', 'D', 'F'][index % 5]}', // 随机成绩 + }; + }); + + // 将 JSON 转化为 Student 对象并返回 + return studentsJson.map((json) => Student.fromJson(json)).toList(); + } + + // 使用 async 和 await 获取数据并更新 UI + Future fetchStudentsData() async { + try { + List students = await fetchStudentsFromNetwork(); // 等待学生信息的返回 + setState(() { + _students = students; // 更新学生列表 + }); + } catch (e) { + setState(() { + _students = []; // 错误发生时清空学生列表 + }); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Student List Example')), + body: _students.isEmpty + ? const Center(child: CircularProgressIndicator()) // 如果列表为空,显示加载指示器 + : ListView.builder( + itemCount: _students.length, // 列表项数量 + itemBuilder: (context, index) { + final student = _students[index]; + return Card( + margin: const EdgeInsets.all(8.0), + elevation: 5, + shadowColor: Colors.grey.withOpacity(0.2), // 设置阴影颜色 + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), // 圆角效果 + ), + child: ListTile( + title: Text(student.name), + subtitle: Text('Age: ${student.age}\nGrade: ${student.grade}'), + ), + ); + }, + ), + ); + } +} + +// 学生模型类 +class Student { + final String name; + final int age; + final String grade; + + Student({required this.name, required this.age, required this.grade}); + + // 从 JSON 数据构造 Student 对象 + factory Student.fromJson(Map json) { + return Student( + name: json['name'], + age: json['age'], + grade: json['grade'], + ); + } +} diff --git a/ohos/asynchronous/lib/completer_future_example.dart b/ohos/asynchronous/lib/completer_future_example.dart new file mode 100644 index 0000000000000000000000000000000000000000..5ecfc38ae179192153cab2dc19db6c0205dc8a31 --- /dev/null +++ b/ohos/asynchronous/lib/completer_future_example.dart @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'dart:async'; + +import 'package:flutter/material.dart'; + +class CompleterFutureExample extends StatefulWidget { + const CompleterFutureExample({Key? key}) : super(key: key); + + @override + _CompleterFutureExampleState createState() => _CompleterFutureExampleState(); +} + +/* + 我们将使用 Completer 来模拟一个异步操作(例如,模拟一个耗时的任务),然后在完成时通知调用者,最后更新界面显示结果。 + + 步骤: + 1、创建一个 Completer 来手动完成 Future。 + 2、模拟一个耗时操作(例如延时操作),然后完成 Future。 + 3、使用 Completer 来控制 Future 的完成时机。 + */ +class _CompleterFutureExampleState extends State { +// 模拟一个自定义 Future 的异步方法 + Future fetchDataWithCompleter() { + // 创建一个 Completer + Completer completer = Completer(); + + // 模拟异步操作,延迟 3 秒 + Future.delayed(const Duration(seconds: 3), () { + // 操作完成后,手动完成 Completer + completer.complete("Data Loaded Successfully!"); + }); + + // 返回 completer 的 Future + return completer.future; + } + + late Future _dataFuture; + + @override + void initState() { + super.initState(); + // 在初始化时调用自定义的 Future + _dataFuture = fetchDataWithCompleter(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Completer Example')), + body: FutureBuilder( + future: _dataFuture, // 使用自定义的 Future + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + // 正在加载 + return const Center(child: CircularProgressIndicator()); + } else if (snapshot.hasError) { + // 错误处理 + return Center(child: Text('Error: ${snapshot.error}')); + } else if (!snapshot.hasData) { + // 数据为空 + return const Center(child: Text('No data available.')); + } else { + // 数据加载成功 + return Center(child: Text(snapshot.data!)); + } + }, + ), + ); + } +} diff --git a/ohos/asynchronous/lib/future_builder_example.dart b/ohos/asynchronous/lib/future_builder_example.dart new file mode 100644 index 0000000000000000000000000000000000000000..48e02174763f5ef84e6093962d64588c3c60e2d4 --- /dev/null +++ b/ohos/asynchronous/lib/future_builder_example.dart @@ -0,0 +1,107 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'package:flutter/material.dart'; + +class FutureBuilderExample extends StatefulWidget { + const FutureBuilderExample({Key? key}) : super(key: key); + + @override + _FutureBuilderExampleState createState() => _FutureBuilderExampleState(); +} + +class _FutureBuilderExampleState extends State { + late Future> _employeeFuture; + + @override + void initState() { + super.initState(); + // 在 initState 中调用并缓存 Future + _employeeFuture = fetchEmployeesFromNetwork(); + } + + // 模拟一个异步网络请求,返回员工数据(30个员工) + Future> fetchEmployeesFromNetwork() async { + await Future.delayed(const Duration(seconds: 2)); // 模拟网络延迟 + + // 模拟返回的员工信息(30个员工) + List> employeesJson = List.generate(30, (index) { + return { + 'name': 'Employee ${index + 1}', + 'position': 'Position ${['Manager', 'Developer', 'Designer', 'HR', 'Tester'][index % 5]}', + 'salary': 3000 + (index % 10) * 500, // 随机薪资 + }; + }); + + // 将 JSON 转化为 Employee 对象并返回 + return employeesJson.map((json) => Employee.fromJson(json)).toList(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('FutureBuilderExample')), + body: FutureBuilder>( + future: _employeeFuture, // 使用缓存的 Future + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + // 正在加载 + return const Center(child: CircularProgressIndicator()); + } else if (snapshot.hasError) { + // 错误 + return Center(child: Text('Error: ${snapshot.error}')); + } else if (!snapshot.hasData || snapshot.data!.isEmpty) { + // 没有数据 + return const Center(child: Text('No employees found.')); + } else { + // 数据加载成功 + List employees = snapshot.data!; + return ListView.builder( + itemCount: employees.length, // 列表项数量 + itemBuilder: (context, index) { + final employee = employees[index]; + return Card( + margin: const EdgeInsets.all(8.0), + child: ListTile( + title: Text(employee.name), + subtitle: Text('Position: ${employee.position}\nSalary: \$${employee.salary}'), + ), + ); + }, + ); + } + }, + ), + ); + } +} + +// 员工模型类 +class Employee { + final String name; + final String position; + final int salary; + + Employee({required this.name, required this.position, required this.salary}); + + // 从 JSON 数据构造 Employee 对象 + factory Employee.fromJson(Map json) { + return Employee( + name: json['name'], + position: json['position'], + salary: json['salary'], + ); + } +} diff --git a/ohos/asynchronous/lib/future_wait_example.dart b/ohos/asynchronous/lib/future_wait_example.dart new file mode 100644 index 0000000000000000000000000000000000000000..dee050d559277b377603cb5c8824505884a78b7b --- /dev/null +++ b/ohos/asynchronous/lib/future_wait_example.dart @@ -0,0 +1,98 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'package:flutter/material.dart'; + +class FutureWaitExample extends StatefulWidget { + const FutureWaitExample({Key? key}) : super(key: key); + + @override + _FutureWaitExampleState createState() => _FutureWaitExampleState(); +} + +/* + 假设我们有三个独立的网络请求,分别获取用户的个人信息、账户信息和通知信息,最后在所有信息都获取完后一起显示。 + + 步骤: + 1、模拟三个不同的异步操作,每个操作返回不同的数据。 + 2、使用 Future.wait 等待所有 Future 完成,统一处理结果。 + 3、在 FutureBuilder 中展示所有请求的结果。 + */ +class _FutureWaitExampleState extends State { + // 模拟获取用户个人信息的异步方法 + Future fetchUserProfile() async { + await Future.delayed(const Duration(seconds: 2)); + return "John Doe, 28 years old"; + } + +// 模拟获取账户信息的异步方法 + Future fetchAccountInfo() async { + await Future.delayed(const Duration(seconds: 2)); + return "Account: #123456789"; + } + +// 模拟获取通知信息的异步方法 + Future fetchNotifications() async { + await Future.delayed(const Duration(seconds: 2)); + return "You have 5 new notifications."; + } + + // 使用 Future.wait 并行执行多个异步操作 + Future> fetchAllData() async { + try { + // 使用 Future.wait 等待所有异步操作完成 + var results = await Future.wait([ + fetchUserProfile(), // 获取用户信息 + fetchAccountInfo(), // 获取账户信息 + fetchNotifications(), // 获取通知信息 + ]); + return results; // 返回所有结果 + } catch (e) { + throw Exception('Failed to fetch data: $e'); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Future.wait Example')), + body: FutureBuilder>( + future: fetchAllData(), // 调用 Future.wait 获取所有数据 + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + // 数据加载中 + return const Center(child: CircularProgressIndicator()); + } else if (snapshot.hasError) { + // 错误处理 + return Center(child: Text('Error: ${snapshot.error}')); + } else if (!snapshot.hasData || snapshot.data!.isEmpty) { + // 数据为空 + return const Center(child: Text('No data available.')); + } else { + // 数据加载成功 + List results = snapshot.data!; + return ListView( + children: [ + ListTile(title: Text('User Profile: ${results[0]}')), + ListTile(title: Text('Account Info: ${results[1]}')), + ListTile(title: Text('Notifications: ${results[2]}')), + ], + ); + } + }, + ), + ); + } +} diff --git a/ohos/asynchronous/lib/main.dart b/ohos/asynchronous/lib/main.dart new file mode 100644 index 0000000000000000000000000000000000000000..da51496aba72ea42bbbcf4d3f39dc95b92646d9f --- /dev/null +++ b/ohos/asynchronous/lib/main.dart @@ -0,0 +1,96 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'package:flutter/material.dart'; + +import 'async_await.dart'; +import 'completer_future_example.dart'; +import 'future_builder_example.dart'; +import 'future_wait_example.dart'; +import 'microtask_example.dart'; +import 'stream_example.dart'; +import 'stream_stream_builder_example.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + home: HomePage(), + ); + } +} + +class HomePage extends StatelessWidget { + HomePage({super.key}); + + final titleList = [ + "async 和 await", + "FutureBuilder", + "Future.wait", + "Completer自定义 Future", + "microtask", + "Stream", + "Stream与StreamBuilder的结合使用" + ]; + + final widgetList = [ + const AsyncAwaitExample(), + const FutureBuilderExample(), + const FutureWaitExample(), + const CompleterFutureExample(), + const MicrotaskExample(), + const StreamExample(), + const StreamStreamBuilderExample() + ]; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text("异步编程"), + ), + body: ListView.builder( + itemCount: titleList.length, + itemBuilder: (context, index) { + return Card( + margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), + elevation: 5, + shadowColor: Colors.grey.withOpacity(0.2), // 设置阴影颜色 + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), // 圆角效果 + ), + child: ListTile( + contentPadding: const EdgeInsets.all(15), + title: Text(titleList[index]), + onTap: () { + // 点击时跳转到不同的页面 + Navigator.push( + context, + MaterialPageRoute(builder: (context) => widgetList[index]), + ); + }, + ), + ); + }, + ), + ); + } +} diff --git a/ohos/asynchronous/lib/microtask_example.dart b/ohos/asynchronous/lib/microtask_example.dart new file mode 100644 index 0000000000000000000000000000000000000000..8c3f57e7ee8799b1c7a54839d0de8b835617b21d --- /dev/null +++ b/ohos/asynchronous/lib/microtask_example.dart @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'dart:async'; + +import 'package:flutter/material.dart'; + +class MicrotaskExample extends StatefulWidget { + const MicrotaskExample({Key? key}) : super(key: key); + + @override + _MicrotaskExampleState createState() => _MicrotaskExampleState(); +} + +/* + Microtasks 是 Dart 语言中的一种特殊任务类型,它们会在当前事件循环的末尾执行。与普通的异步任务(Future)不同,Microtasks 具有以下特点: + + 1、优先级高于 Future: Microtasks 的执行优先级高于 Future,也就是说,即使有一个正在执行的 Future,如果有 Microtasks 需要执行,它们也会先于 Future 执行。 + 2、立即执行: 当 Microtasks 被添加到 event queue 中时,它们会立即执行,而不会等待当前事件循环结束。 + 3、同步执行: 与 Future 不同,Microtasks 是同步执行的,它们会在当前事件循环的末尾,一个接一个地执行完毕。 + */ +class _MicrotaskExampleState extends State { + String _status = "Waiting..."; +//按钮点击事件 + void _onPressed() { + _status = "Waiting..."; + _status = '$_status\n Start'; + // 添加一个 Microtask + scheduleMicrotask(() { + _status = '$_status\n Microtask 1'; + }); + + // 添加一个 Future + Future(() { + setState(() { + _status = '$_status\n Future'; + }); + }); + + // 添加另一个 Microtask + scheduleMicrotask(() { + _status = '$_status\n Microtask 2'; + }); + _status = '$_status\n End'; + } + + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Microtask Example')), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(_status), + const SizedBox(height: 20), + ElevatedButton( + onPressed: () { + _onPressed(); + // // 点击按钮后,使用一个 Microtask 更新状态 + // scheduleMicrotask(() { + // setState(() { + // _status = "Microtask triggered by button!"; + // }); + // }); + }, + child: const Text('Trigger Microtask'), + ), + ], + ), + ), + ); + } +} diff --git a/ohos/asynchronous/lib/stream_example.dart b/ohos/asynchronous/lib/stream_example.dart new file mode 100644 index 0000000000000000000000000000000000000000..18c43326ed1a1e7f33a731d446583a386aa5b6b0 --- /dev/null +++ b/ohos/asynchronous/lib/stream_example.dart @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'dart:async'; + +import 'package:flutter/material.dart'; + +class StreamExample extends StatefulWidget { + const StreamExample({Key? key}) : super(key: key); + + @override + _StreamExampleState createState() => _StreamExampleState(); +} + +/* + 在这个示例中,我们创建了一个 Stream,每秒钟发出一个新的整数。我们使用 StreamSubscription 来手动监听这个 Stream,并在数据到达时更新 UI。 + + 步骤: + 1、创建一个 Stream,模拟每秒钟发送一个整数。 + 2、手动订阅这个 Stream,并在数据到达时更新 UI。 + */ +class _StreamExampleState extends State { + late StreamSubscription _subscription; + String _status = "Waiting..."; + + // 创建一个 Stream,模拟每秒钟发送一个整数 + Stream numberStream() async* { + int count = 0; + while (true) { + await Future.delayed(const Duration(seconds: 1)); // 模拟延迟 + yield count++; // 每秒钟发出一个新的整数 + } + } + + @override + void initState() { + super.initState(); + + // 手动订阅 Stream + _subscription = numberStream().listen( + (data) { + setState(() { + _status = "Number: $data"; // 更新状态显示最新的数字 + }); + }, + onError: (error) { + setState(() { + _status = "Error: $error"; // 错误处理 + }); + }, + onDone: () { + setState(() { + _status = "Stream closed"; // Stream 完成 + }); + }, + ); + } + + @override + void dispose() { + // 取消订阅 + _subscription.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Stream Example')), + body: Center( + child: Text(_status, style: const TextStyle(fontSize: 48)), + ), + ); + } +} diff --git a/ohos/asynchronous/lib/stream_stream_builder_example.dart b/ohos/asynchronous/lib/stream_stream_builder_example.dart new file mode 100644 index 0000000000000000000000000000000000000000..dfd72947cb4a707cef6bb1daa5ef85a5bce14c22 --- /dev/null +++ b/ohos/asynchronous/lib/stream_stream_builder_example.dart @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'package:flutter/material.dart'; + +class StreamStreamBuilderExample extends StatefulWidget { + const StreamStreamBuilderExample({Key? key}) : super(key: key); + + @override + _StreamStreamBuilderExampleState createState() => _StreamStreamBuilderExampleState(); +} + +/* + 假设我们有一个应用程序,它接收一系列的数据(例如,模拟的传感器数据),并通过 Stream 持续传递这些数据项。在这个例子中,我们将模拟一个持续发出整数的 Stream,并通过 StreamBuilder 在 Flutter UI 中显示这些数据。 + + 步骤: + 1、创建一个 Stream,它每隔一秒钟发出一个整数。 + 2、使用 StreamBuilder 在 Flutter UI 中动态展示接收到的数据。 + */ +class _StreamStreamBuilderExampleState extends State { + // 创建一个 Stream,模拟每秒钟发送一个整数 + Stream numberStream() async* { + int count = 0; + while (true) { + await Future.delayed(const Duration(seconds: 1)); // 模拟延迟 + yield count++; // 每秒钟发出一个新的整数 + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Stream与StreamBuilder的结合使用')), + body: StreamBuilder( + stream: numberStream(), // 监听 Stream + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + // 等待 Stream 数据 + return const Center(child: CircularProgressIndicator()); + } else if (snapshot.hasError) { + // 错误处理 + return Center(child: Text('Error: ${snapshot.error}')); + } else if (!snapshot.hasData) { + // 数据为空 + return const Center(child: Text('No data')); + } else { + // 数据更新,显示 Stream 中的最新整数 + return Center( + child: Text('Number: ${snapshot.data}', style: const TextStyle(fontSize: 48)), + ); + } + }, + ), + ); + } +} diff --git a/ohos/asynchronous/ohos/.gitignore b/ohos/asynchronous/ohos/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6ca13b3170eec5dd5ac5ad7f1c4dd0118845f473 --- /dev/null +++ b/ohos/asynchronous/ohos/.gitignore @@ -0,0 +1,19 @@ +/node_modules +/oh_modules +/local.properties +/.idea +**/build +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +**/.test +*.har +**/BuildProfile.ets +**/oh-package-lock.json5 + +**/src/main/resources/rawfile/flutter_assets/ +**/libs/arm64-v8a/libapp.so +**/libs/arm64-v8a/libflutter.so +**/libs/arm64-v8a/libvmservice_snapshot.so diff --git a/ohos/asynchronous/ohos/AppScope/app.json5 b/ohos/asynchronous/ohos/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..daa7d34e4f91ae51b5ac46da1dc08a453a94641c --- /dev/null +++ b/ohos/asynchronous/ohos/AppScope/app.json5 @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "app": { + "bundleName": "com.example.asynchronous", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} diff --git a/ohos/asynchronous/ohos/AppScope/resources/base/element/string.json b/ohos/asynchronous/ohos/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..3ccd72122973a803a74b66f59ea7b99adc694276 --- /dev/null +++ b/ohos/asynchronous/ohos/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "asynchronous" + } + ] +} diff --git a/ohos/asynchronous/ohos/AppScope/resources/base/media/app_icon.png b/ohos/asynchronous/ohos/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/ohos/asynchronous/ohos/AppScope/resources/base/media/app_icon.png differ diff --git a/ohos/asynchronous/ohos/build-profile.json5 b/ohos/asynchronous/ohos/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..0d8b167e6cea7b597c49097ab38d3e9ff785a24f --- /dev/null +++ b/ohos/asynchronous/ohos/build-profile.json5 @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS", + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/.gitignore b/ohos/asynchronous/ohos/entry/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2795a1c5b1fe53659dd1b71d90ba0592eaf7e043 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/.gitignore @@ -0,0 +1,7 @@ + +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/build-profile.json5 b/ohos/asynchronous/ohos/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..633d360fbc91a3186a23b66ab71b27e5618944cb --- /dev/null +++ b/ohos/asynchronous/ohos/entry/build-profile.json5 @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "apiType": 'stageMode', + "buildOption": { + }, + "targets": [ + { + "name": "default", + "runtimeOS": "HarmonyOS" + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/hvigorfile.ts b/ohos/asynchronous/ohos/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..894fc15c6b793f085e6c8506e43d719af658e8ff --- /dev/null +++ b/ohos/asynchronous/ohos/entry/hvigorfile.ts @@ -0,0 +1,17 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +export { hapTasks } from '@ohos/hvigor-ohos-plugin'; diff --git a/ohos/asynchronous/ohos/entry/oh-package.json5 b/ohos/asynchronous/ohos/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..803b25293388deda7b9a05a21b5aeadeb716b4d5 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/oh-package.json5 @@ -0,0 +1,9 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": {} +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/main/ets/entryability/EntryAbility.ets b/ohos/asynchronous/ohos/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..8bc48be8773196f34cccb15cf517f87f5c6b94d2 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,24 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { FlutterAbility, FlutterEngine } from '@ohos/flutter_ohos'; +import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant'; + +export default class EntryAbility extends FlutterAbility { + configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + GeneratedPluginRegistrant.registerWith(flutterEngine) + } +} diff --git a/ohos/asynchronous/ohos/entry/src/main/ets/pages/Index.ets b/ohos/asynchronous/ohos/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..1125f9fdd95f4310a182c1c9e3680f37f73686c9 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import common from '@ohos.app.ability.common'; +import { FlutterPage } from '@ohos/flutter_ohos' + +let storage = LocalStorage.getShared() +const EVENT_BACK_PRESS = 'EVENT_BACK_PRESS' + +@Entry(storage) +@Component +struct Index { + private context = getContext(this) as common.UIAbilityContext + @LocalStorageLink('viewId') viewId: string = ""; + + build() { + Column() { + FlutterPage({ viewId: this.viewId }) + } + } + + onBackPress(): boolean { + this.context.eventHub.emit(EVENT_BACK_PRESS) + return true + } +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets b/ohos/asynchronous/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets new file mode 100644 index 0000000000000000000000000000000000000000..40f130cd4ad66fbe957f382dc9d34c384d33341c --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { FlutterEngine, Log } from '@ohos/flutter_ohos'; + +/** + * Generated file. Do not edit. + * This file is generated by the Flutter tool based on the + * plugins that support the Ohos platform. + */ + +const TAG = "GeneratedPluginRegistrant"; + +export class GeneratedPluginRegistrant { + + static registerWith(flutterEngine: FlutterEngine) { + try { + } catch (e) { + Log.e( + TAG, + "Tried to register plugins with FlutterEngine (" + + flutterEngine + + ") failed."); + Log.e(TAG, "Received exception while registering", e); + } + } +} diff --git a/ohos/asynchronous/ohos/entry/src/main/module.json5 b/ohos/asynchronous/ohos/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..7bbf78b18f39991b1404061c7437538c7d532bb7 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/module.json5 @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "requestPermissions": [ + {"name" : "ohos.permission.INTERNET"}, + ] + } +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/main/resources/base/element/color.json b/ohos/asynchronous/ohos/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/main/resources/base/element/string.json b/ohos/asynchronous/ohos/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..2bc11e63381c5197f666b2c2d0cd9aec9ab0cab0 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "asynchronous" + } + ] +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/main/resources/base/media/icon.png b/ohos/asynchronous/ohos/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/ohos/asynchronous/ohos/entry/src/main/resources/base/media/icon.png differ diff --git a/ohos/asynchronous/ohos/entry/src/main/resources/base/profile/main_pages.json b/ohos/asynchronous/ohos/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/ohos/asynchronous/ohos/entry/src/main/resources/en_US/element/string.json b/ohos/asynchronous/ohos/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..2bc11e63381c5197f666b2c2d0cd9aec9ab0cab0 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "asynchronous" + } + ] +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/main/resources/zh_CN/element/string.json b/ohos/asynchronous/ohos/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f225e9b9e6a0b6f6f8f1ed5ca17e0ca4258f1838 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "模块描述" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "asynchronous" + } + ] +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/ets/test/Ability.test.ets b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..25d4c71ff3cd584f5d64f6f8c0ac864928c234c4 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import hilog from '@ohos.hilog'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' + +export default function abilityTest() { + describe('ActsAbilityTest', function () { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(function () { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(function () { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(function () { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(function () { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain',0, function () { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc' + let b = 'b' + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b) + expect(a).assertEqual(a) + }) + }) +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/ets/test/List.test.ets b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..f4140030e65d20df6af30a6bf51e464dea8f8aa6 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,20 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import abilityTest from './Ability.test' + +export default function testsuite() { + abilityTest() +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..4ca645e6013cfce8e7dbb728313cb8840c4da660 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import hilog from '@ohos.hilog'; +import { Hypium } from '@ohos/hypium'; +import testsuite from '../test/List.test'; +import window from '@ohos.window'; + +export default class TestAbility extends UIAbility { + onCreate(want, launchParam) { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate'); + hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? ''); + hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:'+ JSON.stringify(launchParam) ?? ''); + var abilityDelegator: any + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var abilityDelegatorArguments: any + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!'); + Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) + } + + onDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage) { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageCreate'); + windowStage.loadContent('testability/pages/Index', (err, data) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', + JSON.stringify(data) ?? ''); + }); + } + + onWindowStageDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageDestroy'); + } + + onForeground() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onForeground'); + } + + onBackground() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onBackground'); + } +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..cef0447cd2f137ef82d223ead2e156808878ab90 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import hilog from '@ohos.hilog'; + +@Entry +@Component +struct Index { + aboutToAppear() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility index aboutToAppear'); + } + @State message: string = 'Hello World' + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('next page') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .width('35%') + .height('5%') + .onClick(()=>{ + }) + } + .width('100%') + } + .height('100%') + } + } \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..1def08f2e9dcbfa3454a07b7a3b82b173bb90d02 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import hilog from '@ohos.hilog'; +import TestRunner from '@ohos.application.testRunner'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +var abilityDelegator = undefined +var abilityDelegatorArguments = undefined + +async function onAbilityCreateCallback() { + hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback'); +} + +async function addAbilityMonitorCallback(err: any) { + hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? ''); +} + +export default class OpenHarmonyTestRunner implements TestRunner { + constructor() { + } + + onPrepare() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare '); + } + + async onRun() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run'); + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility' + let lMonitor = { + abilityName: testAbilityName, + onAbilityCreate: onAbilityCreateCallback, + }; + abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback) + var cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName + var debug = abilityDelegatorArguments.parameters['-D'] + if (debug == 'true') + { + cmd += ' -D' + } + hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd); + abilityDelegator.executeShellCommand(cmd, + (err: any, d: any) => { + hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? ''); + }) + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end'); + } +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/module.json5 b/ohos/asynchronous/ohos/entry/src/ohosTest/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..fab77ce2e0c61e3ad010bab5b27ccbd15f9a8c96 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/module.json5 @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "module": { + "name": "entry_test", + "type": "feature", + "description": "$string:module_test_desc", + "mainElement": "TestAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:test_pages", + "abilities": [ + { + "name": "TestAbility", + "srcEntry": "./ets/testability/TestAbility.ets", + "description": "$string:TestAbility_desc", + "icon": "$media:icon", + "label": "$string:TestAbility_label", + "exported": true, + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ] + } + ] + } +} diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/element/color.json b/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/element/string.json b/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..65d8fa5a7cf54aa3943dcd0214f58d1771bc1f6c --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_test_desc", + "value": "test ability description" + }, + { + "name": "TestAbility_desc", + "value": "the test ability" + }, + { + "name": "TestAbility_label", + "value": "test label" + } + ] +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/media/icon.png b/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/media/icon.png differ diff --git a/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json b/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..b7e7343cacb32ce982a45e76daad86e435e054fe --- /dev/null +++ b/ohos/asynchronous/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "testability/pages/Index" + ] +} diff --git a/ohos/asynchronous/ohos/hvigor/hvigor-config.json5 b/ohos/asynchronous/ohos/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..541ba35711b75986f9295410ee38fdb8f2572878 --- /dev/null +++ b/ohos/asynchronous/ohos/hvigor/hvigor-config.json5 @@ -0,0 +1,20 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "modelVersion": "5.0.0", + "dependencies": { + } +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/hvigorfile.ts b/ohos/asynchronous/ohos/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f2d2aafe6d6a3a71a9944ebd0c91fbc308ac9d1 --- /dev/null +++ b/ohos/asynchronous/ohos/hvigorfile.ts @@ -0,0 +1,21 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} \ No newline at end of file diff --git a/ohos/asynchronous/ohos/oh-package.json5 b/ohos/asynchronous/ohos/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..ff2024ccc08619426741ccc63782cff70e300d05 --- /dev/null +++ b/ohos/asynchronous/ohos/oh-package.json5 @@ -0,0 +1,33 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "modelVersion": "5.0.0", + "name": "asynchronous", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + "@ohos/flutter_ohos": "file:./har/flutter.har" + }, + "devDependencies": { + "@ohos/hypium": "1.0.6" + }, + "overrides": { + "@ohos/flutter_ohos": "file:./har/flutter.har" + } +} diff --git a/ohos/asynchronous/pubspec.yaml b/ohos/asynchronous/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ffc369922b9cfb9380f6e8e95dd97ceb8d59560 --- /dev/null +++ b/ohos/asynchronous/pubspec.yaml @@ -0,0 +1,103 @@ +# Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: asynchronous +description: A new Flutter project. +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: '>=2.19.6 <3.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/ohos/asynchronous/test/widget_test.dart b/ohos/asynchronous/test/widget_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..87d040d17dc41ac640ceff9e9806002918731444 --- /dev/null +++ b/ohos/asynchronous/test/widget_test.dart @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:asynchronous/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +}