Flutter 获取网络数据及渲染列表

原文链接: http://www.cnblogs.com/joe235/p/11274316.html

还是通过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 {
    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 tiles = [];//先建一个数组用于存放循环生成的widget
      for(var item in formList) {
        tiles.add(
          new Column(
              children: [
                  Image.network(item['image'],width: 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: [
                    buildGrid(),
                  ],
              )     
            )
        );
    }
}

 

效果图:

Flutter 获取网络数据及渲染列表_第1张图片

转载于:https://www.cnblogs.com/joe235/p/11274316.html

你可能感兴趣的:(Flutter 获取网络数据及渲染列表)