Flutter进阶—网络与本地异步加载资源

通过网络加载JSON文件的实例

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void _networkLoading() {
  // 将给定标头的HTTP GET请求发送到给定的URL,并注册回调,参数为HTTP响应
  http.get('https://domokit.github.io/examples/stocks/data/stock_data_2.json').then((http.Response response) {
    // 响应的主体作为字符串返回
    String netdata = response.body;
    // JsonDecoder类解析JSON字符串并构建相应的对象
    JsonDecoder decoder = new JsonDecoder();
    // 将给定的JSON字符串输入转换为其对应的对象
    List<List<String>> json = decoder.convert(netdata);
    // 输出给定的JSON数据
    print(json[0][1]);
  });
}

Flutter进阶—网络与本地异步加载资源_第1张图片

通过异步加载本地Json资源,需要先在pubspec.yaml文件添加资源文件,然后再通过异步加载资源文件,以下为实例

name: menus_demo
description: A new flutter project.
dependencies:
  flutter:
    sdk: flutter
flutter:
  uses-material-design: true
  assets:
    - assets/config.json
import 'dart:convert';
import 'dart:async' show Future;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}
void _loadJson() {
  loadAsset().then((value){
    JsonDecoder decoder = new JsonDecoder();
    List<List<String>> json = decoder.convert(value);
    print('姓名:'+json[0][0]+',年龄:'+json[0][1]);
  });
}

这里写图片描述

你可能感兴趣的:(dart,flutter,Flutter教程)