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(
           100,
          height: 100,
          image: AssetImage("assets/avatar.jpg"),
        )
        ],
      ),
    ),
      

这个相同简单,直接使用AssetImage接口获取就行

原文地址:https://www.cnblogs.com/dengxiaoning/p/11742362.html