还是通过Dio包调用远程接口获取数据,这里返回值为一个Future,
这个对象支持一个等待回掉方法then
。
示例代码如下:
import 'package:flutter/material.dart'; import 'package:dio/dio.dart'; class TestPage extends StatefulWidget { @override _TestPageState createState() => _TestPageState(); } class _TestPageState extends State<TestPage> { List formList; initState() { super.initState(); getHttp().then((val){ setState(() { formList = val['result'].toList(); }); }); } Future getHttp() async{ try{ Response response; Dio dio = new Dio(); response =await dio.get("https://www.easy-mock.com/mock/5d3914e09388917915bccb2e/shopapp/shopapp_dh"); print(response); return response.data; }catch(e){ return print(e); } } Widget buildGrid() { List<Widget> tiles = [];//先建一个数组用于存放循环生成的widget for(var item in formList) { tiles.add( new Column( children: <Widget>[ Image.network(item['image'], 500,height: 100,fit: BoxFit.cover,), Text(item['title']) ] ) ); } return Column( children:tiles ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('循环渲染组件案例'), ), body: SingleChildScrollView( child: Column( children: <Widget>[ buildGrid(), ], ) ) ); } }
效果图: