在Flutter 2.x版本中将Http返回的结果转Dart稍微和前几个版本有些许差异,具体演示说明如下。
Ps:在这里我用一个网上的开源api来示例

请求接口地址:https://v1.hitokoto.cn/
接口返回的Json对象如下:

{
    "id":3931,
    "uuid":"afc68395-6e1c-429c-b322-f1b7f4d43eba",
    "hitokoto":"嘿!活着是件很好的事",
    "type":"e",
    "from":"原创",
    "from_who":null,
    "creator":"Great old ones",
    "creator_uid":2073,
    "reviewer":0,
    "commit_from":"web",
    "created_at":"1538200036",
    "length":10
}

json对应的类对象如下:

class OneSentence {

  int id;

  String? hitokoto;

  String uuid;

  String? type;

  String? from;

  String? fromWho;

  String? creator;

  int? creatorUid;

  int reviewer;

  String? commitFrom;

  String? createdAt;

  int length;

  OneSentence(
      this.id,
      this.hitokoto,
      this.uuid,
      this.type,
      this.from,
      this.fromWho,
      this.creator,
      this.creatorUid,
      this.reviewer,
      this.commitFrom,
      this.createdAt,
      this.length);

  factory OneSentence.fromJson(Map<String, dynamic> json) {
    return OneSentence(
        json['id'],
        json['hitokoto'],
        json['uuid'],
        json['type'],
        json['from'],
        json['from_who'],
        json['creator'],
        json['creator_uid'],
        json['reviewer'],
        json['commit_from'],
        json['created_at'],
        json['length']);
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['hitokoto'] = this.hitokoto;
    data['uuid'] = this.uuid;
    data['type'] = this.type;
    data['from'] = this.from;
    data['from_who'] = this.fromWho;
    data['creator'] = this.creator;
    data['creator_uid'] = this.creatorUid;
    data['reviewer'] = this.reviewer;
    data['commit_from'] = this.commitFrom;
    data['created_at'] = this.createdAt;
    data['length'] = this.length;
    return data;
  }

}

请求http获取api结果:

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

import 'package:flutter/material.dart';
import 'package:flutter_demo/bean/OneSentence.dart';

class HttpPage extends StatefulWidget {
  const HttpPage({Key? key}) : super(key: key);

  @override
  _HttpPageState createState() => _HttpPageState();
}

class _HttpPageState extends State<HttpPage> {
  String _text = "";
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Http请求"),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(Icons.arrow_back),
        ),
      ),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(child: ListView(
              children: [
                Text(_text),
                ElevatedButton(
                    onPressed: () => httpGet('https://v1.hitokoto.cn/', getOneSentence),
                    child: Text('一言API')),

              ],
            ))
          ],
        ),
      ),
    );
  }

  // 解析并转换
  OneSentence getOneSentence(String res) {
    String _result = res;
    JsonCodec j = new JsonCodec();
    OneSentence ons = OneSentence.fromJson(j.decode(_result));
    setState(() {
      this._text = j.encode(ons.toJson());
    });
    return ons;
  }

  // 请求API并获取请求结果
  void httpGet(String url, Function call) {
    HttpClient _httpClient = new HttpClient();
    String _result = "";
     _httpClient.getUrl(Uri.parse(url))
        .then((HttpClientRequest request) => request.close())
        .then((HttpClientResponse response)  {
          if(response.statusCode == 200) {
            response.transform(utf8.decoder).join().then((value) {
              _result = value;
              call(_result);
            } );
          } else {
            print('error');
            _result = 'error';
            call(_result);
          }
        }
    );

  }

  
  
}

标签: Flutter, Flutter 2.0, Flutter Http请求结果转Dart

添加新评论