Home > database >  How to turn part of the response from Dio into a variable in Flutter/Dart?
How to turn part of the response from Dio into a variable in Flutter/Dart?

Time:07-30

Using Dio, I make a specific request to the site:

final response = await Dio().get(
…
print(response); //Just to see my response

Here is the response from the console:

I/flutter ( 4594): {"records":[{"id":"recrNhzWnPdiSFaCs","createdTime":"2022-07-28T15:45:23.000Z","fields":{"Name":"Cactus ","Data":"11.5","App":"The Best App","Current":"98789fg43"}}]}

I am satisfied with the data. They are correct. For further work, I only need the recrNhzWnPdiSFaCs value. I want to pass it to a variable that will be used in another part of the code. How to do it?

Edit1. Using var decodedString = json.decode(response.data.toString()); does not cause any errors in the code. But on startup, the following appears in the console:

I/flutter ( 4594): {"records":[{"id":"recrNhzWnPdiSFaCs","createdTime":"2022-07-28T15:45:23.000Z","fields":{"Name":"Cactus ","First":"11.5","App":"The Best App","Current":"98789fg43"}}]}
E/flutter ( 4594): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Unexpected character (at character 2)
E/flutter(4594): {records: [{id: recrNhzWnPdiSFaCs, createdTime: 2022-07-28T15:45:23.000Z, f...
E/flutter ( 4594): ^
E/flutter ( 4594):
E/flutter ( 4594): #0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
E/flutter ( 4594): #1 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:913:48)
E/flutter ( 4594): #2 _parseJson (dart:convert-patch/convert_patch.dart:35:10)
E/flutter ( 4594): #3 JsonDecoder.convert (dart:convert/json.dart:612:36)
E/flutter ( 4594): #4 JsonCodec.decode (dart:convert/json.dart:216:41)
E/flutter(4594): #5 _MainWidgetState.airtableFind(package:example/main.dart:214:32)
E/flutter ( 4594): <asynchronous suspension>
E/flutter ( 4594):

And here is the whole code in case I made a mistake somewhere:

//Airtable (find a record)
  void airtableFind() async {
    try {
      final response = await Dio().get(
        'https://api.airtable.com/v0/' projectBase '/' recordName,
        queryParameters: {
          // 'filterByFormula': 'SEARCH("Cactus",{Name})' // Searches the value 'Cactus' in the {'Short description'} field.
          'filterByFormula': 'SEARCH(' '"' testName '"' ',{Name})' // Searches the value 'Cactus' in the {'Short description'} field.
          // 'filterByFormula': 'SEARCH(' testName ',{Name})' // Searches the value 'Cactus' in the {'Short description'} field.
        },
        options: Options(
          contentType: 'Application/json',
          headers: {
            'Authorization': 'Bearer' ' ' apiKey,
            'Accept': 'Application/json',
          },
        ),
      );

      // TODO: Whatever you want to do with the response. A good practice is to transform it into models and than work with them
      print(response);
      // String fromString = response;

      // String response1 = '{"records":[{"id":"recrNhzWnPdiSFaCs","createdTime":"2022-07-28T15:45:23.000Z","fields":{"Name":"Cactus ","Data":"11.5","App":"The Best App","Current":"98789fg43"}}]}';
      var decodedString = json.decode(response.data.toString());
      // final decodedJSON = json.decode(response.body);
      // final decodedJSON = json.decode(utf8.decode(response.bodyBytes));

      print(decodedString['records'][0]['id']);
      String id = decodedString['records'][0]['id'];


    } on DioError catch (e) {
      // TODO: Error handling
      if (e.response != null) {
        // print(e.response.data);
        print(e);
      } else {
        // print(e.request);
        print(e.message);
      }
    }
  }

Edit2. When I use final decodedString = json.decode(response.data); I see the following errors in the console:

I/flutter( 4289): {"records":[{"id":"recrNhzWnPdiSFaCs","createdTime":"2022-07-28T15:45:23.000Z","fields":{"Name":"Cactus ","First":"11.5","App":"The Best App","Current":"98789fg43"}}]}
E/flutter ( 4289): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
E/flutter(4289): #0 _MainWidgetState.airtableFind(package:example/main.dart:217:50)
E/flutter ( 4289): <asynchronous suspension>

When I use var decodedString = json.decode(response.data.toString()); the following errors appear in the console:

I/flutter( 4289): {"records":[{"id":"recrNhzWnPdiSFaCs","createdTime":"2022-07-28T15:45:23.000Z","fields":{"Name":"Cactus ","First":"11.5","App":"The Best App","Current":"98789fg43"}}]}
E/flutter ( 4289): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Unexpected character (at character 2)
E/flutter(4289): {records: [{id: recrNhzWnPdiSFaCs, createdTime: 2022-07-28T15:45:23.000Z, f...
E/flutter ( 4289): ^
E/flutter ( 4289):
E/flutter ( 4289): #0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
E/flutter ( 4289): #1 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:913:48)
E/flutter ( 4289): #2 _parseJson (dart:convert-patch/convert_patch.dart:35:10)
E/flutter ( 4289): #3 JsonDecoder.convert (dart:convert/json.dart:612:36)
E/flutter ( 4289): #4 JsonCodec.decode (dart:convert/json.dart:216:41)
E/flutter(4289): #5 _MainWidgetState.airtableFind(package:example/main.dart:217:32)
E/flutter ( 4289): <asynchronous suspension>

CodePudding user response:

You can use json.decode to convert the response to a json value. Then you can fetch its values with respective keys like

String response = '{"records":[{"id":"recrNhzWnPdiSFaCs","createdTime":"2022-07-28T15:45:23.000Z","fields":{"Name":"Cactus ","Data":"11.5","App":"The Best App","Current":"98789fg43"}}]}';
  var decodedString  = json.decode(response);
  print(decodedString['records'][0]['id']);
//Output : recrNhzWnPdiSFaCs

Don't miss to import

import 'dart:convert';

CodePudding user response:

You can achieve your purpose by decoding your JSON.

final decodedJSON = json.decode(response.data);

, also if your response contains a UTF-8 encoding (has for example Persian characters), you can use:

final decodedJSON = json.decode(utf8.decode(response.bodyBytes));

CodePudding user response:

dio body name is data so the decoding would be as following

final decodedJSON = json.decode(response.data);
  • Related