Flutter Example HTTP GET

《Flutter Example HTTP GET》

import 'package:flutter/material.dart';
import 'package:http/http.dart';--http包文件
import 'dart:async';--异步操作
import 'dart:convert';--JSON转换

void main() => runApp(new MaterialApp(
      home: new MyGetHttpDate(),
    ));

class MyGetHttpDate extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyGetHttpDateState();
}

class MyGetHttpDateState extends State<MyGetHttpDate> {
  final String url = "https://swapi.co/api/people";
  List data;

  Future<String> getJsonData() async {
    var response =
        await get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    print(response);
    setState(() {
      var dataConvertedToJSON = jsonDecode(response.body);
      data = dataConvertedToJSON['results'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Center(
          child: new Text("Retrieve JSON Data via HTTP GET"),
        ),
      ),
      body: new ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, int index) {
          return new Container(
            child: new Center(
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  new Card(
                    child: new Container(
                      child: new Text(data[index]['name'],
                          style: new TextStyle(
                              fontSize: 20.0, color: Colors.lightBlueAccent)),
                      padding: EdgeInsets.all(15.0),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    this.getJsonData();
  }
}

    原文作者:三只仓鼠
    原文地址: https://www.jianshu.com/p/faa6a2d19a1a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞