Search code examples
jsonflutterdio

Flutter populate dropdown with Json response, using dio plugin for server call


Getting below Format exception when I am trying to decode Json response. Please help out. Unhandled Exception: FormatException: Unexpected character (at character 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');
  }

Solution

  • Edit add dio parse example and parse picture

    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});
    

    Assume dio already return correct json string is

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

    Step 1: Parse jsonString with payload class

    List<Payload> payload = payloadFromJson(jsonString);
    

    payload class

    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,
          };
    }
    

    Step 2: transfer this payload to required map of DropdownMenuItem

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

    Step 3: populate 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(),
                    ),
    

    full code

    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