Flutter 网络请求

一、Flutter JSON 字符串和 Map 类型的
转换
import ‘dart:convert‘
var mapData={"name":"张三","age":"20"};
var strData=‘{"name":"张三","age":"20"}‘;
print(json.encode(mapData)); //Map 转换成 Json 字符串
print(json.decode(strData)); //Json 字符串转化成 Map 类型
 
 
二、使用 http 库进行网络请求
请参考官方文档:https://pub.dev/packages/http 
 
案例代码
 
import ‘package:flutter/material.dart‘;import ‘package:http/http.dart‘ as http;import ‘dart:convert‘;class HttpPage extends StatefulWidget {  HttpPage({Key key}) : super(key: key);  _HttpDemoState createState() => _HttpDemoState();}class _HttpDemoState extends State {  List _list=[];  @override  initState() {    // TODO: implement initState    super.initState();    this._getData();  }  _getData() async{    var apiUrl="http://a.itying.com/api/productlist";    var result=await http.get(apiUrl);    if(result.statusCode==200){      print(result.body);      setState(() {        this._list=json.decode(result.body)["result"];      });    }else{      print("失败${result.statusCode}");    }  }  @override  Widget build(BuildContext context) {    return Scaffold(        appBar: AppBar(          title: Text("请求数据Demo"),        ),        body: this._list.length>0?ListView(          children: this._list.map((value){            return ListTile(              title: Text(value["title"]),            );          }).toList(),        ):Text("加载中...")    );  }}

相关推荐