flutter填坑之旅(配置本地資源文件)


一、添加單個資源文件

項目下創建一個assets目錄,在該目錄下存放對應的資源文件(json、image、…)

pubspec.yaml文件中配置資源文件路徑(注意縮進要與上下文一直)


  assets:
    - assets/home.json
    

二、添加多個資源文件

pubspec.yaml文件中配置資源文件路徑


  assets:
    - assets/home.json
    - assets/avatar.jpg
    

或者直接將assets目錄下所有文件添加


  assets:
    - assets/

三、 json讀取


  static Future<String> fetch() async{

	  rootBundle.loadString('assets/home.json').then((response){
	      var result = json.decode(response);
	      return result;
	    });

  }

這種方式發現頁面無法獲得數據

在這里插入圖片描述
調試發現數據已經取到,但是在這個異步過程中頁面渲染已經結束

修改方法(使用await)


  static Future<String> fetch() async{
  
    final response = await rootBundle.loadString('assets/home.json');
    var result = json.decode(response);
    
    return result;

//  rootBundle.loadString('assets/home.json').then((response){
//      var result = json.decode(response);
//      return result;
//    });

 }
 

頁面數據獲取成功

四、image 讀取


    body: Center(
      // Center is a layout widget. It takes a single child and positions it
      // in the middle of the parent.
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
        Image(
          width: 100,
          height: 100,
          image: AssetImage("assets/avatar.jpg"),
        )
        ],
      ),
    ),
      

這個相同簡單,直接使用AssetImage接口獲取就行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM