Flutter使用Json响应填充下拉列表,使用dio插件进行服务器调用

时间:2019-10-08 06:51:11

标签: json flutter dio

当我尝试解码Json响应时,获取以下Format异常。请帮忙。 未处理的异常:FormatException:意外字符(在字符3处)         [{table_no:1},{table_no:2},{table_no:3}]

[
    {
        "table_no": "1"
    },
    {
        "table_no": "2"
    },
    {
        "table_no": "3"
    }
]

Future<Response> pos_client_table() async {

  String url =
      'https://xxxxxx.com/api/v1/table?branch_id=1';
  Response response;
  Dio dio = new Dio();
  dio.options.headers = {'Authorization': prefs.getString('posclient_token')};

  try {
    response = await dio.get(url);

    var jso = json.decode(response.toString());

    Fluttertoast.showToast(
        msg: "$jso",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);

  } catch (e) {
    print(e);
  }

  return response;
}

 void CallTableUrl() async {
    Response response = await pos_client_table();
    List<Map> _myJson = json.decode(response.toString());
    showInSnackBar('$_myJson');
  }

1 个答案:

答案 0 :(得分:0)

编辑添加dio解析示例并解析图片

Response response;
Dio dio = new Dio();
response = await dio.get("http://yoursite");
print(response);
print(response.data.toString());

List<Payload> payload = payloadFromJson(response.data);
print({payload[0].tableNo});

假定dio已经返回正确的json字符串

String jsonString = '[{"table_no": "1"},{"table_no": "2"},{"table_no": "3"}]';

步骤1:使用有效负载类解析jsonString

List<Payload> payload = payloadFromJson(jsonString);

有效载荷类

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

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

class Payload {
  String tableNo;

  Payload({
    this.tableNo,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        tableNo: json["table_no"],
      );

  Map<String, dynamic> toJson() => {
        "table_no": tableNo,
      };
}

第2步:将此有效负载传输到DropdownMenuItem的必需映射

for (var i = 0; i < payload.length; i++) {
      _myJson.add({'id': payload[i].tableNo, 'name': payload[i].tableNo});
    }

第3步:填充DropdownMenuItem

DropdownButton<String>(
                  isDense: true,
                  hint: Text("${payload[0].tableNo}"),
                  value: _mySelection,
                  onChanged: (String Value) {
                    setState(() {
                      _mySelection = Value;
                    });
                    print(_mySelection);
                  },
                  items: _myJson.map((Map map) {
                    return DropdownMenuItem<String>(
                      value: map["id"].toString(),
                      child: Text(
                        map["name"],
                      ),
                    );
                  }).toList(),
                ),

完整代码

import 'package:flutter/material.dart';
import 'dart:convert';

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

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

class Payload {
  String tableNo;

  Payload({
    this.tableNo,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        tableNo: json["table_no"],
      );

  Map<String, dynamic> toJson() => {
        "table_no": tableNo,
      };
}

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

String jsonString = '[{"table_no": "1"},{"table_no": "2"},{"table_no": "3"}]';
List<Payload> payload = payloadFromJson(jsonString);

List<Map> _myJson = [];

class _MyHomePageState extends State<MyHomePage> {
  String _mySelection;

  @override
  void initState() {
    for (var i = 0; i < payload.length; i++) {
      _myJson.add({'id': payload[i].tableNo, 'name': payload[i].tableNo});
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Container(
              height: 500.0,
              child: Center(
                child: DropdownButton<String>(
                  isDense: true,
                  hint: Text("${payload[0].tableNo}"),
                  value: _mySelection,
                  onChanged: (String Value) {
                    setState(() {
                      _mySelection = Value;
                    });
                    print(_mySelection);
                  },
                  items: _myJson.map((Map map) {
                    return DropdownMenuItem<String>(
                      value: map["id"].toString(),
                      child: Text(
                        map["name"],
                      ),
                    );
                  }).toList(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

enter image description here

enter image description here