Flutter加載本地圖片躺坑記錄

步驟

1.在根目錄建立一個文件夾,名稱建議叫images
2.在此文件夾下建立兩個文件夾,一個為2.0x,一個為3.0x,分別放置2倍圖和3倍圖,正常的圖片直接放置到images文件夾下

images.png

3.在pubspec.yaml文件中申明本地圖片:

# The following section is specific to Flutter.
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/tupian.png

這里有一個坑,先前這個assets是官方注釋的,我是直接就解開了,然后把下方的圖片路徑寫好,編譯卻出現(xiàn)如下錯誤:

Error on line 29, column 4 of pubspec.yaml: Expected a key while parsing a block mapping.
   assets:
   ^

pub get failed (65)

原因是assets前面有一個空格,assets需要與上面的uses-material-design對齊,把它對齊重新編譯就好了。

4.在代碼中調(diào)用Image.asset()方法加載本地圖片展示,示例:

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return new MaterialApp(
      title: 'Welcome to Flutter',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Welcome to Flutter'),
        ),
        body: new Center(
          child: new Image.asset("images/tupian.png")  //路徑要寫全
        ),
      ),
    );
  }
}

如果是加載第三方依賴庫中的圖片,需要在路徑后面申明包名路徑:

new Image.asset("images/tupian.png", package: 'my_package')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容