一、添加單個資源文件
項目下創建一個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
接口獲取就行