【问题标题】:Displaying the image in Flutter works once在 Flutter 中显示图像一次
【发布时间】:2020-02-28 18:48:56
【问题描述】:

当我在文件中设置图像并将其设置在资产中时,我遇到了颤振Image.assets 的问题:

`颤动: 使用材料设计:真实 资产:

  • 图像/facebook.png`

当我把它放在我的代码中时:

Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Image.asset(
          "images/facebook.png"

        ),
        Text(
          '$_counter',
          style: Theme.of(context).textTheme.display1,
        ),
      ],
    ),
  ),

并运行它,它运行良好 但我第二次运行代码时,它没有显示 这是我得到的错误:

I/flutter (4784): ══╡ 图像资源服务捕获的异常 ╞═════════════════════════════════════════════════ ═══ I/颤振 ( 4784):解析图像时引发以下断言: I/flutter (4784):无法加载资产:AssetManifest.json。 . . 我/颤振(4784):#381 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:969:5) I/flutter (4784): #382 RenderObjectToWidgetAdapter.attachToRenderTree。 (包:flutter/src/widgets/binding.dart:915:17) I/flutter ( 4784):#383 BuildOwner.buildScope (包:flutter/src/widgets/framework.dart:2328:19) I/flutter ( 4784):#384 RenderObjectToWidgetAdapter.attachToRenderTree (包:flutter/src/widgets/binding.dart:914:13)I/flutter(4784): #385 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:795:7) I/flutter (4784): #386 runApp (package:flutter/src/widgets/binding.dart:845:7) I/flutter (4784): #387 main (package:flutter_app/main.dart:4:16) I/flutter (4784): #388 _runMainZoned.. (dart:ui/hooks.dart:229:25) I/flutter ( 4784):#393 _runMainZoned。 (dart:ui/hooks.dart:221:5) I/flutter (4784): #394
_start隔离。 (dart:isolate-patch/isolate_patch.dart:305:19) I/flutter (4784): #395 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12) I/flutter (4784): (从包 dart:async 中省略了 7 帧)I/flutter(4784):图像 提供者:AssetImage(捆绑:null,名称:“images/facebook.png”) I/flutter(4784):图像配置:ImageConfiguration(捆绑: PlatformAssetBundle#b5447(), devicePixelRatio: 1.5, I/flutter (4784): 语言环境:en_US,textDirection:TextDirection.ltr,平台:android) 我/颤振(4784): ══════════════════════════════════════════════════ ══════════════════════════════════════════════════

【问题讨论】:

    标签: image flutter assets


    【解决方案1】:

    第 1 步: - 创建一个名为 assets 的目录,如下图所示。并将图像添加到此目录。

    第 2 步:

    -将您的目录添加到 pubspec.yaml。这是对该目录的所有图像的支持。

    第 3 步:

    -在终端上运行此命令。

    flutter pub get
    

    第 4 步:

    -这样写代码。如果要控制图像大小,请使用 height 和 width 属性。

    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Image.asset("assets/facebook.png"),
          ),
        );
      }
    }
    

    结果:

    【讨论】:

      【解决方案2】:

      这个问题最近发生在我身上。正如@Mohamed Adel 回答的那样,您必须保留正确的空格。 您还可以包含整个文件夹eg: images

      flutter:
      
      [2 whitespaces]assets:
      [4 whitespaces]- images/
      

      如果图片文件夹有子文件夹eg: images/products/

      flutter:
      
      [2 whitespaces]assets:
      [4 whitespaces]- images/products
      

      pubspec.yaml 中,使用空格总是比使用制表符更安全

      【讨论】:

        【解决方案3】:

        1).创建名为 images 的文件夹 2).add 要添加的图片 3). 像这样在 pubspec 中添加 资产: - 图像/xyz.png 4)点击包获取 5)运行应用程序(首先杀死应用程序并运行)。

        【讨论】:

          【解决方案4】:

          确保在 pubspec.yaml 中使用 2 或 4 个空格(避免制表符)作为缩进。

          你的 pubspec.yaml 必须是这样的

          flutter:
            uses-material-design: true
            assets:
              - images/facebook.png
          

          不是这样的

          flutter:
            uses-material-design: true
            assets:
                - images/facebook.png # error
          

          或者像这样

          flutter:
            uses-material-design: true
            assets:
            - images/facebook.png # also error
          

          运行
          flutter clean
          flutter pub get
          在您的终端中

          【讨论】:

          • 我意识到这一点,但问题是:图像显示良好,我第一次运行代码时没有出错,但是当我点击重新加载按钮时,图像消失了。 .
          • 尝试删除并重新创建您的图像/文件夹
          【解决方案5】:

          检查一下

          assets:
             - images/facebook.png
          

          确保你有完全一样的空格

          flutter:
          
          [2 whitespaces or 1 tab]assets:
          [4 whitespaces or 2 tabs]- images/facebook.png
          

          每个空间都很重要

          【讨论】:

          • 图像显示良好,我第一次运行代码时没有出错,但是当我点击重新加载按钮时,图像消失了
          • 能否给我看一下pubspec.yaml的完整代码和图片的完整代码
          【解决方案6】:

          我的代码:

          import 'package:flutter/material.dart';
          import 'dart:io';
          import 'package:image_picker/image_picker.dart';
          void main() => runApp(MyApp());
          
          class MyApp extends StatelessWidget {
            // 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: MyHomePage(title: 'myApp'),
              );
            }
          }
          
          class MyHomePage extends StatefulWidget {
            MyHomePage({Key key, this.title}) : super(key: key);
          
            final String title;
          
            @override
            _MyHomePageState createState() => _MyHomePageState();
          }
          
          class _MyHomePageState extends State<MyHomePage> {
            File imageFile;
            int _counter = 0;
            Color red = Colors.red;
             _incrementCounter() async{
               var picture = await ImagePicker.pickImage(source: ImageSource.camera);
          
              this.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.
                imageFile = picture;
                _counter++;
                print("work");
              });
            }
          
            @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(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        "images/facebook.png"
          
                      ),
                      Text(
                        '$_counter',
                        style: Theme.of(context).textTheme.display1,
                      ),
                    ],
                  ),
                ),
                floatingActionButton: FloatingActionButton(
                  onPressed: _incrementCounter,
                  tooltip: 'Increment',
                  child: Icon(Icons.add),
                ), // This trailing comma makes auto-formatting nicer for build methods.
              );
            }
          }
          

          我的 pubspec.yaml:

          name: flutter_app
          description: A new Flutter application.
          
          # 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 used as CFBundleVersion.
          # Read more about iOS versioning at
          # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
          version: 1.0.0+1
          
          environment:
            sdk: ">=2.1.0 <3.0.0"
          
          dependencies:
            flutter:
              sdk: flutter
            image_picker:
          
          
            # The following adds the Cupertino Icons font to your application.
            # Use with the CupertinoIcons class for iOS style icons.
            cupertino_icons: ^0.1.2
          
          dev_dependencies:
            flutter_test:
              sdk: flutter
          
          
          # 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.
          flutter:
            uses-material-design: true
            assets:
             - images/
          
            # 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
          

          【讨论】:

            猜你喜欢
            • 2020-03-13
            • 1970-01-01
            • 2020-12-30
            • 2013-04-11
            • 1970-01-01
            • 2019-05-31
            • 2018-01-14
            • 1970-01-01
            • 2021-12-30
            相关资源
            最近更新 更多