【问题标题】:image doesn't display on the app even though it was in assets folder即使图像位于资产文件夹中,图像也不会显示在应用程序上
【发布时间】:2023-04-03 12:31:01
【问题描述】:

我在资产文件夹中添加了图像文件。 但是当我运行应用程序时,图像根本不显示。 并且没有任何错误消息。 我不知道为什么我看不到我添加的图片。 (当然,这不是白色的图片。这是正常的图片。) 请告诉我原因。

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Title'),
      ),
      body: Center(
        child: GestureDetector(
          onTap: (){
            Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => HeroDetailPage()),
            );
          },
          child: Hero(
            tag: 'image',
            child: Image.asset(
                'assets/sample.jpg',
              width: 100,
              height: 100,
            ),
          ),
        ),
      ),
    );
  }
}

class HeroDetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hero Detail'),
      ),
      body: Hero(
        tag: 'image',
        child: Image.asset('assets/sample.jpg'),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter assets display


    【解决方案1】:

    请先检查:https://flutter.dev/docs/development/ui/assets-and-images

    在那里你可以找到这个:

    Flutter 使用位于项目根目录的 pubspec.yaml 文件来识别应用所需的资产。

    这是一个例子:

    flutter:
      assets:
        - assets/my_icon.png
        - assets/background.png
    

    要包含目录下的所有资产,请以 / 字符结尾指定目录名称:

    flutter:
      assets:
        - directory/
        - directory/subdirectory/
    

    【讨论】:

      【解决方案2】:

      要将资产添加到您的应用程序,请在您的 pubspec.yaml 文件中添加一个资产部分,如下所示:

      assets:
      - assets/
      

      【讨论】:

        【解决方案3】:

        首先将您的图像文件添加到 pubspec.yml 文件中

        assets:
            - assets/sample.jpg
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-07
          • 2023-03-22
          • 2015-02-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-01
          相关资源
          最近更新 更多