Flutter - Request data using http and show it

Keywords: JSON snapshot network github

follow https://github.com/jiangkang/flutter-system Learn more about Flutter

PPP that cannot make network requests is not a real APP. Flutter currently does not have a very reliable open source library (unsatisfactory) for network requests. Please use http temporarily to fulfill simple network requests.

Design sketch

data model

/// Model: Picture List Response
class ImageResponse {
  final int code;
  final String message;
  final List<Map<String, dynamic>> result;

  ImageResponse(this.code, this.message, this.result);

  factory ImageResponse.fromJson(Map<String, dynamic> json) => ImageResponse(
      json["code"],
      json["message"],
      List<Map<String, dynamic>>.from(json["result"]));
}

/// Model: Picture Data
class ImageBean {
  final String img;
  final String publishedAt;

  ImageBean({this.img, this.publishedAt});

  factory ImageBean.fromJson(Map<String, String> json) {
    return ImageBean(img: json["img"], publishedAt: json["publishedAt"]);
  }
}

The important thing to note here is the dynamic type. Don't force it or you will get an error.Why do I need to do manual parsing here?First, because it's simple, and second, because Flutter doesn't support reflection, it doesn't deserialize very well (json_serializable generates code, which isn't very satisfying and is ignored here).

Interface Request

import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart';

const String HOST_DEMO = "https://api.apiopen.top";

const String defaultPage = "0";

const String defaultCount = "30";

///Get a list of pictures
Future<ImageResponse> fetchImages() async {
  return getImages().then((response) {
    return ImageResponse.fromJson(json.decode(response.body));
  }).catchError((error) {
    throw HttpException("statusCode: ${error.toString()}");
  });
}

Future<Response> getImages() => get("$HOST_DEMO/getImages",
    headers: {"page": defaultPage, "count": defaultCount});

Note the json transformation, and as for the request parameters, you can construct a map yourself.

Parse response data and display

SafeArea(
          child: FutureBuilder<ImageResponse>(
        future: fetchImages(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                padding: EdgeInsets.only(left: 10, right: 10, top: 6),
                itemCount: snapshot.data.result.length,
                itemBuilder: (context, index) {
                  final Map<String, dynamic> bean =
                      (snapshot.data.result)[index];
                  return Card(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(4)),
                    child: InkWell(
                      child: FadeInImage.assetNetwork(
                        image: bean["img"] ?? IMG_URL0,
                        placeholder: "images/loading.gif",
                      ),
                      onTap: () {
                        NavUtils.openWebView(context,
                            "https://github.com/jiangkang/flutter-system");
                      },
                    ),
                  );
                });
          } else if (snapshot.hasError) {
            return Center(child: Text("Error occurs! ${snapshot.error}"));
          }
          return Center(child: CircularProgressIndicator());
        },
      ))

You'll use FutureBuilder to host the data, then simply show a list of pictures.

Complete Code

Complete Code

Posted by MaTT on Tue, 30 Jul 2019 10:16:03 -0700