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("加载中...") ); }}
相关推荐
xiaoseyihe 2020-11-16
xiaoseyihe 2020-11-16
世事一场大梦 2020-10-18
jling 2020-10-14
chenyuping 2020-10-06
kyelu 2020-08-03
KAIrving 2020-08-02
xiesheng 2020-08-02
liushall 2020-07-18
shenwenjie 2020-07-07
yunfenglee 2020-07-08
83520298 2020-07-06
Jonderwu 2020-07-05
xiaobater 2020-07-04
范范 2020-06-28
newusb 2020-06-28