前提准备

  1. 因为在网上进行了一些查询,然后发现一些大佬推荐说Android Studio比较更好用,所以这一篇用的是Android Studio来做的,去网上参考了不少教程,做下来感觉也能适应。
  2. 关于Android Studio的相关配置,可以参考的这篇,我觉得非常详细,不容易出错Android Studio安装配置教程

1.使用Android Studio创建新项目

1.1插件准备

在进行完上面那个教程的配置过后,要下载Dart和Flutter这两个插件,在Android Studio中打开setting,点击plugins,如图(找不到可以搜索)
在这里插入图片描述

1.2新建项目

  • 插件下载完过后会出现一个New flutter Project选项,点击这个,如图
    在这里插入图片描述
  • 会提示你选择SDK路径,将我们之前同步的flutter的路径导入就好了
  • 按照项目创建项目名,选择所需要的平台(我看到的教程建议都选),然后点击create
  • 然后我们需要打开终端,查看是否是正确的鸿蒙的Flutter SDK
flutter --version

在这里插入图片描述

  • 在终端创建鸿蒙的项目,输入
flutter create --platform ohos .

1.3项目分包

  • 选中lib目录选择New再选择新建文件夹,新建以下的目录,每个目录的作用如图所示(这里我参照的一位大佬的教程)
    在这里插入图片描述

2.使用Dio实现网络请求

2.1添加dio的库

在pubspec.yaml添加dio的库,这里要和flutter对齐

  • dio: ^5.5.0+1
  • provider: ^6.1.2
    请添加图片描述

2.2使用Dio进行网络请求并渲染UI

这里做的一个猫咪照片的

2.2.1 猫咪图片数据模型

  • lib/viewmodels/cat_model.dart
  • 代码如下
class CatModel {
  final String id;
  final String url;
  final int width;
  final int height;

  CatModel({
    required this.id,
    required this.url,
    required this.width,
    required this.height,
  });

  factory CatModel.fromJson(Map<String, dynamic> json) {
    return CatModel(
      id: json['id'] ?? '',
      url: json['url'] ?? '',
      width: json['width'] ?? 0,
      height: json['height'] ?? 0,
    );
  }

  Map<String, dynamic> toJson() => {
    'id': id,
    'url': url,
    'width': width,
    'height': height,
  };
}

2.2.2 猫咪API服务

  • 文件路径:lib/api/cat_api.dart
  • 代码如下
import 'package:app1/utils/http_util.dart';
import 'package:app1/viewmodels/cat_model.dart';
import 'package:app1/contents/api_constants.dart';

class CatApi {
  static final HttpUtil _http = HttpUtil();

  // 获取猫咪图片列表(基础方法)
  static Future<List<CatModel>> getCatImages({
    int limit = 1,  // 默认只获取1张
    int? page,
    String? order,
    bool? hasBreeds,
    String? breedIds,
    String? categoryIds,
    int? subId,
  }) async {
    try {
      final Map<String, dynamic> queryParams = {
        'limit': limit,
      };

      // 添加可选参数
      if (page != null) queryParams['page'] = page;
      if (order != null) queryParams['order'] = order;
      if (hasBreeds != null) queryParams['has_breeds'] = hasBreeds ? 1 : 0;
      if (breedIds != null) queryParams['breed_ids'] = breedIds;
      if (categoryIds != null) queryParams['category_ids'] = categoryIds;
      if (subId != null) queryParams['sub_id'] = subId;

      final data = await _http.get(
        '${ApiConstants.catBaseUrl}${ApiConstants.catImagesEndpoint}',
        queryParams: queryParams,
      );

      if (data is List) {
        return data.map((json) => CatModel.fromJson(json)).toList();
      } else {
        throw Exception('返回数据格式错误');
      }
    } catch (e) {
      rethrow;
    }
  }

  // 获取单张猫咪图片(简化方法)
  static Future<CatModel> getSingleCat() async {
    final cats = await getCatImages(limit: 1); // ✅ 调用上面定义的方法
    return cats.first;
  }

  // 可选:获取多张猫咪图片
  static Future<List<CatModel>> getMultipleCats(int count) async {
    return await getCatImages(limit: count);
  }
}

2.2.3 猫咪页面调用

  • 文件:lib/pages/Cats/index.dart
  • 代码如下
import 'package:flutter/material.dart';
import 'package:app1/api/cat_api.dart';
import 'package:app1/viewmodels/cat_model.dart';
import 'package:app1/components/cat_card.dart';

class CatsPage extends StatefulWidget {
  const CatsPage({super.key});

  
  State<CatsPage> createState() => _CatsPageState();
}

class _CatsPageState extends State<CatsPage> {
  CatModel? _cat; // ✅ 只保存一张图片
  bool _isLoading = false;
  String? _error;

  
  void initState() {
    super.initState();
    _fetchCat(); // ✅ 只获取一张
  }

  Future<void> _fetchCat() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final cat = await CatApi.getSingleCat(); // ✅ 调用获取单张的方法
      setState(() {
        _cat = cat;
      });
    } catch (e) {
      setState(() {
        _error = e.toString();
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('随机猫咪 🐱'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _fetchCat, // ✅ 刷新时也只获取一张
          ),
        ],
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            Text('加载失败: $_error'),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _fetchCat,
              child: const Text('重新获取'),
            ),
          ],
        ),
      );
    }

    if (_cat == null) {
      return const Center(child: Text('暂无猫咪图片'));
    }

    // ✅ 只显示一张图片,居中显示
    return SingleChildScrollView(
      child: Center(
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CatCard(cat: _cat!),
              const SizedBox(height: 20),
              // 添加一些操作按钮
              Wrap(
                spacing: 12,
                children: [
                  ElevatedButton.icon(
                    onPressed: _fetchCat,
                    icon: const Icon(Icons.refresh),
                    label: const Text('换一张'),
                  ),
                  OutlinedButton.icon(
                    onPressed: () {
                      // 可以添加保存或分享功能
                    },
                    icon: const Icon(Icons.download),
                    label: const Text('保存'),
                  ),
                ],
              ),
              const SizedBox(height: 20),
              // 显示详细信息
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '图片信息',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text('ID: ${_cat!.id}'),
                    Text('宽度: ${_cat!.width} 像素'),
                    Text('高度: ${_cat!.height} 像素'),
                    Text('URL: ${_cat!.url}'),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

2.2.4 猫咪卡片组件

  • 文件:lib/components/cat_card.dart
  • 代码如下
import 'package:flutter/material.dart';
import 'package:app1/viewmodels/cat_model.dart';

class CatCard extends StatelessWidget {
  final CatModel cat;

  const CatCard({
    super.key,
    required this.cat,
  });

  
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      child: Column(
        children: [
          // 猫咪图片
          ClipRRect(
            borderRadius: const BorderRadius.vertical(
              top: Radius.circular(12),
            ),
            child: SizedBox(
              width: double.infinity,
              height: 200,
              child: Image.network(
                cat.url,
                fit: BoxFit.cover,
                loadingBuilder: (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Center(
                    child: CircularProgressIndicator(
                      value: loadingProgress.expectedTotalBytes != null
                          ? loadingProgress.cumulativeBytesLoaded /
                          loadingProgress.expectedTotalBytes!
                          : null,
                    ),
                  );
                },
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[100],
                    child: const Center(
                      child: Icon(
                        Icons.image_not_supported,
                        size: 50,
                        color: Colors.grey,
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
          // 猫咪信息
          Padding(
            padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '尺寸: ${cat.width} × ${cat.height}',
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'ID: ${cat.id}', // ✅ 修复:直接显示完整ID,不截取
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

2.2.5 路由配置文件

  • 文件:lib/routes/index.dart
  • 代码如下
import 'package:flutter/material.dart';
import 'package:app1/pages/Login/index.dart';
import 'package:app1/pages/Main/index.dart';
import 'package:app1/pages/Cats/index.dart';

// 管理路由
import 'package:flutter/material.dart';
import 'package:app1/pages/Login/index.dart';
import 'package:app1/pages/Main/index.dart';
import 'package:app1/pages/Cats/index.dart';

// 返回App根组件
Widget getRootWidget() {
  return MaterialApp(
    // 命名路由
    initialRoute: '/', // 默认首页
    routes: getRootRoutes(),
  );
}

// 返回该App的路由配置
Map<String, Widget Function(BuildContext)> getRootRoutes() {
  return {
    '/': (context) => MainPage(), // 主页路由
    '/login': (context) => LoginPage(), // 登录路由
    '/cats': (context) => CatsPage(), // 猫咪图库路由
  };
}

2.2.6 猫咪API常量配置

  • 文件:lib/contents/api_constants.dart
  • 代码如下
class ApiConstants {
  // 猫咪API
  static const String catBaseUrl = 'https://api.thecatapi.com/v1';
  static const String catImagesEndpoint = '/images/search';

  // 默认配置
  static const int defaultPageSize = 10;
  static const int defaultTimeout = 15; // 秒
}

2.2.7 封装Dio网络请求

  • 文件:lib/utils/http_util.dart
  • 代码如下
import 'package:dio/dio.dart';

class HttpUtil {
  static final HttpUtil _instance = HttpUtil._internal();
  late Dio _dio;

  factory HttpUtil() => _instance;

  HttpUtil._internal() {
    _dio = Dio(BaseOptions(
      connectTimeout: const Duration(seconds: 15),
      receiveTimeout: const Duration(seconds: 15),
    ));
  }

  Dio get dio => _dio;

  // 通用GET请求
  Future<dynamic> get(String endpoint, {Map<String, dynamic>? queryParams}) async {
    try {
      final response = await _dio.get(endpoint, queryParameters: queryParams);
      return response.data;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  String _handleError(DioException e) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        return '网络连接超时,请检查网络';
      case DioExceptionType.badResponse:
        return '服务器错误: ${e.response?.statusCode}';
      case DioExceptionType.cancel:
        return '请求已取消';
      default:
        return '网络错误: ${e.message}';
    }
  }
}

2.2.8 状态管理

  • 文件:lib/stores/cat_store.dart
  • 代码如下
import 'package:flutter/material.dart';
import 'package:app1/api/cat_api.dart';
import 'package:app1/viewmodels/cat_model.dart';

class CatStore extends ChangeNotifier {
  List<CatModel> _cats = [];
  bool _isLoading = false;
  String? _error;
  int _currentPage = 1;

  List<CatModel> get cats => _cats;
  bool get isLoading => _isLoading;
  String? get error => _error;
  int get currentPage => _currentPage;

  // 获取猫咪图片
  Future<void> fetchCats({
    int limit = 10,
    bool hasBreeds = false,
    bool loadMore = false,
  }) async {
    if (!loadMore) {
      _currentPage = 1;
    }

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final newCats = await CatApi.getCatImages(
        limit: limit,
        page: _currentPage,
        hasBreeds: hasBreeds,
      );

      if (loadMore) {
        _cats.addAll(newCats);
      } else {
        _cats = newCats;
      }

      _currentPage++;
    } catch (e) {
      _error = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 刷新数据
  Future<void> refresh() async {
    await fetchCats(limit: _cats.length);
  }

  // 清空数据
  void clear() {
    _cats = [];
    _error = null;
    _currentPage = 1;
    notifyListeners();
  }
}

2.2.9 App入口主页

  • 文件:lib/pages/Main/index.dart
  • 代码如下
import 'package:flutter/material.dart';

class MainPage extends StatelessWidget {
  const MainPage({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Qing Mall'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '欢迎使用 Qing Mall',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 40),
            // 猫咪图库入口
            SizedBox(
              width: 200,
              child: ElevatedButton.icon(
                onPressed: () {
                  Navigator.pushNamed(context, '/cats');
                },
                icon: const Icon(Icons.pets),
                label: const Text('猫咪图库'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ),
            const SizedBox(height: 16),
            // 登录入口
            SizedBox(
              width: 200,
              child: OutlinedButton(
                onPressed: () {
                  Navigator.pushNamed(context, '/login');
                },
                child: const Text('用户登录'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

2.2.10 登录页面

  • 文件:lib/pages/Login/index.dart
    (登录页面的空壳子,有页面结构但需要填充具体登录功能)
  • 代码如下
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('登录'),),
      body: Center(child: Text('登录页面'),),
    );
  }
}

2.2.11 主程序入口文件

  • 文件:lib/main.dart
  • 代码如下
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:app1/routes/index.dart';
import 'package:app1/stores/cat_store.dart';

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => CatStore()),
        // 可以添加更多Provider
      ],
      child: getRootWidget(),
    ),
  );
}

2.2.12 lib目录

现在的lib目录大概是这样的
在这里插入图片描述

3.运行项目

鸿蒙

打开DevEco Studio,点击对应的ohos文件,选择模拟器运行如图
在这里插入图片描述

安卓

点击绿色三角形进行运行即可
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/710b5b19017e48aea9ff3c00b642b6d6.png

总结

今天从零开始构建一个Flutter鸿蒙项目的完整过程,使用Dio库实现网络请求,调用猫咪图片API,并展示在鸿蒙和安卓双平台上,虽然是参照的网上的各种教程,但是还是感觉有些收获的。
欢迎加入开源鸿蒙跨平台社区:
https://openharmonycrossplatform.csdn.net

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐