在flutter中基于POST方法的json结果返回小部件

时间:2019-09-09 04:52:56

标签: json flutter dart flutter-layout

我的dashboard.dart看起来像这样

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:abc/utils/connection_config.dart';
import 'package:abc/screens/loginpage.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';

class Dash extends StatefulWidget {
  @override
  DashState createState() => DashState();
}

class DashState extends State<Dash> {
  Future reportList;

  @override
  void initState() {
    super.initState();
    reportList = getDashboardData();
  }

  getDashboardData() async {
    var fromtime = 1567449000000;
    var totime = 1567770486144;
    var mtype = "internet";

    http.Response response = await http.post(dashboardURL,
        headers: {"Content-type": "application/json"},
        body: json.encode({
          "fromTime": fromtime,
          "mtype": mtype,
          "must": [
            {"msg_status": "0"}
          ],
          "toTime": totime
        }));
    switch (response.statusCode) {
      case 200:
        String dashboardResult = response.body;
        var collection = json.decode(dashboardResult);
        return collection;
        break;
      case 403:
      case 401:
        return null;
      default:
        return 1;
    }
  }

  Widget getContents(BuildContext context, var data) { //here I want to return the widget for each entry in hits array
    Widget _widget;
    _widget = SingleChildScrollView(
      child: SingleChildScrollView(
        child: Container(
          child: ,
          ),
        ),
      );
    return _widget;
  }



//function that iterates over the list


  getRefreshScaffold() {
    return Center(
      child: RaisedButton(
        onPressed: () {
          setState(() {
            reportList = getDashboardData();
          });
        },
        child: Text('Refresh, Network issues.'),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: reportList,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
          case ConnectionState.active:
            return Center(
              child: CircularProgressIndicator(),
            );
          case ConnectionState.done:
            var data = snapshot.data;
            if (snapshot.hasData && !snapshot.hasError) {
              return Container(
                child: getContents(context, snapshot.data),
              );
            } else if (data == null) {
              return Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Text("Timeout! Log back in to continue"),
                    Padding(
                      padding: EdgeInsets.all(25.0),
                    ),
                    RaisedButton(
                      onPressed: () {
                        setState(() {
                          token = null;
                        });
                        Navigator.of(context).pushReplacement(
                          CupertinoPageRoute(
                              builder: (BuildContext context) => LoginPage()),
                        );
                      },
                      child: Text('Login Again!'),
                    ),
                  ],
                ),
              );
            } else {
              getRefreshScaffold();
            }
        }
      },
    );
  }
}

在这里,我正在点击一个提供json的api,我需要遍历以下内容,

{
..... some other data

    "hitsArray": [
            {
                "tt": 1567566438144,
                "status": "0",
                "count": 2257056,
                "status_count": 2257053
            },
            {
                "tt": 1567566438144,
                "status": "1",
                "count": 2257056,
                "status_count": 3
            }
        ],
    ...some other data
    }

我想做的是遍历json结果中的hitsarray并在小部件中显示每个条目。 但是我没有得到如何遍历json数据并分配一个小部件来显示它的方法,我尽了最大努力,但无法获得它。

1 个答案:

答案 0 :(得分:1)

将您的json字符串粘贴到https://app.quicktype.io/,您可以获得正确的解析逻辑,并且可以使用ListView显示

您可以在期间修改延迟以模拟网络延迟。

await new Future.delayed(new Duration(seconds: 10));

如果您的json字符串如下所示

[
            {
                "tt": 1567566438144,
                "status": "0",
                 "count": 2257056,
                "status_count": 2257053
            }
            ,
            {
                "tt": 1567566438144,
                "status": "1",
                "count": 2257056,
                "status_count": 3
            }
]

quicktype的逻辑

// To parse this JSON data, do
//
//     final hitsArray = hitsArrayFromJson(jsonString);

import 'dart:convert';

List<HitsArray> hitsArrayFromJson(String str) => List<HitsArray>.from(json.decode(str).map((x) => HitsArray.fromJson(x)));

String hitsArrayToJson(List<HitsArray> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class HitsArray {
    int tt;
    String status;
    int count;
    int statusCount;

    HitsArray({
        this.tt,
        this.status,
        this.count,
        this.statusCount,
    });

    factory HitsArray.fromJson(Map<String, dynamic> json) => HitsArray(
        tt: json["tt"],
        status: json["status"],
        count: json["count"],
        statusCount: json["status_count"],
    );

    Map<String, dynamic> toJson() => {
        "tt": tt,
        "status": status,
        "count": count,
        "status_count": statusCount,
    };
}

使用FutureBuilder和ListView演示完整的代码

import 'dart:async';

import 'package:flutter/material.dart';
// To parse this JSON data, do
//
//     final hitsArray = hitsArrayFromJson(jsonString);

import 'dart:convert';

List<HitsArray> hitsArrayFromJson(String str) => List<HitsArray>.from(json.decode(str).map((x) => HitsArray.fromJson(x)));

String hitsArrayToJson(List<HitsArray> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class HitsArray {
  int tt;
  String status;
  int count;
  int statusCount;

  HitsArray({
    this.tt,
    this.status,
    this.count,
    this.statusCount,
  });

  factory HitsArray.fromJson(Map<String, dynamic> json) => HitsArray(
    tt: json["tt"],
    status: json["status"],
    count: json["count"],
    statusCount: json["status_count"],
  );

  Map<String, dynamic> toJson() => {
    "tt": tt,
    "status": status,
    "count": count,
    "status_count": statusCount,
  };
}


void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    var futureBuilder = new FutureBuilder(
      future: _getData(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return new Text('loading...');
          default:
            if (snapshot.hasError)
              return new Text('Error: ${snapshot.error}');
            else
              return createListView(context, snapshot);
        }
      },
    );

    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Home Page"),
      ),
      body: futureBuilder,
    );
  }

  Future<List<HitsArray>> _getData() async {
    String jsonString = ' [    {      "tt": 1567566438144,    "status": "0",    "count": 2257056,    "status_count": 2257053    }    ,    {    "tt": 1567566438144,    "status": "1",    "count": 2257056,    "status_count": 3    }    ]';
    var values = hitsArrayFromJson(jsonString);
    //throw new Exception("Danger Will Robinson!!!");

    await new Future.delayed(new Duration(seconds: 1));

    return values;
  }

  Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
    List<HitsArray> values = snapshot.data;
    return new ListView.builder(
      itemCount: values.length,
      itemBuilder: (BuildContext context, int index) {
        return new Column(
          children: <Widget>[
            new ListTile(
              title: new Text(' count ${values[index].count.toString()}'),
              subtitle: new Text('status count ${values[index].statusCount.toString()}'),
            ),
            new Divider(height: 2.0,),
          ],
        );
      },
    );
  }
}

enter image description here

enter image description here