HarmonyOS 鸿蒙Next flutter无法加载图片

发布于 1周前 作者 caililin 来自 鸿蒙OS

HarmonyOS 鸿蒙Next flutter无法加载图片 问题描述:鸿蒙化 flutter 使用 cached_network_image 无法加载图片

操作步骤:
已参考 issue 里的回复修改代码,但仍然无法加载图片
参考:https://gitee.com/openharmony-sig/flutter_flutter/issues/I9R10N?from=project-issue

2 回复

参考下面这个示例代码看下

name: f_ohos_test

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
  cached_network_image: ^3.2.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^2.0.0

dependency_overrides:
  path_provider:
    git:
      url: "https://gitee.com/openharmony-sig/flutter_packages.git"
      path: "packages/path_provider/path_provider"
  sqflite:
    git:
      url: "https://gitee.com/openharmony-sig/flutter_sqflite.git"
      path: "sqflite"

# 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

  # This section identifies your Flutter project as a module meant for
  # embedding in a native host app. These identifiers should _not_ ordinarily
  # be changed after generation - they are used to ensure that the tooling can
  # maintain consistency when adding or modifying assets and plugins.
  # They also do not have any bearing on your native host application's
  # identifiers, which may be completely independent or the same as these.
  module:
    iosBundleIdentifier: com.example.flutterModule

main.dart

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.
  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    getTemporaryDirectory();
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('You have pushed the button this many times:'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            Container(
              width: 300,
              height: 300,
              color: Colors.yellow,
              child: CachedNetworkImage(
                imageUrl: 'https://pics7.baidu.com/feed/a71ea8d3fd1f4134f8bb678f9181afc4d3c85edb.jpeg',
                fit: BoxFit.fill,
              ),
              // child: Image.network(
              //   'https://pics7.baidu.com/feed/a71ea8d3fd1f4134f8bb678f9181afc4d3c85edb.jpeg'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

手机版本Next0.0.26

[!] Flutter (Channel dev, 3.7.12-ohos, on Microsoft Windows [版本 10.0.19045.4412], locale zh-CN)
  • Flutter version 3.7.12-ohos on channel dev at C:\Users\LWX1307250\flutter_flutter
  ! Upstream repository https://gitee.com/openharmony-sig/flutter_flutter.git is not a standard remote.
    Set environment variable "FLUTTER_GIT_URL" to https://gitee.com/openharmony-sig/flutter_flutter.git to dismiss
    this error.
  • Framework revision 01908698db (6 days ago), 2024-07-11 12:42:01 +0000
  • Engine revision 1a65d409c7
  • Dart version 2.19.6
  • DevTools version 2.20.1
  • Pub download mirror https://pub.flutter-io.cn
  • Flutter download mirror https://storage.flutter-io.cn
  • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly
    to perform update checks and upgrades.

更多关于HarmonyOS 鸿蒙Next flutter无法加载图片的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


针对HarmonyOS鸿蒙系统中Next flutter无法加载图片的问题,可能的原因及解决方法如下:

  1. 资源路径错误: 检查图片资源的路径是否正确。在Flutter中,图片资源通常放置在assets文件夹下,并在pubspec.yaml文件中正确配置。确保路径与配置一致,且文件名无误。

  2. 权限问题: 如果图片来源于外部存储,需要确保应用已获取读取外部存储的权限。在鸿蒙系统中,权限管理可能有所不同,需参考鸿蒙开发文档进行配置。

  3. 图片格式不支持: 检查图片格式是否为Flutter所支持。常见支持的图片格式包括PNG、JPEG等。如果图片格式不被支持,尝试转换格式。

  4. 网络图片加载问题: 如果加载的是网络图片,确保网络连接正常,且图片URL有效。同时,检查是否有网络请求相关的限制或错误。

  5. Flutter引擎或插件问题: 确保Flutter引擎和相关插件版本与鸿蒙系统兼容。有时,插件或引擎的更新可能修复了加载图片的问题。

如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html

回到顶部