0

Below is my code where I need to access the 'code' json object from response body and show the alert but my code is failing and throwing Invalid response(executing only the else part). The execution is failing to enter the if part.How do I fix it? Json response is as follows:{ "synchData": { "message": "Retailer already synced", "code": 1 } }

 Future<Either<Failure, Q>> parseResponse<Q, R>(
    http.Response response, ComputeCallback<String, R> callback) async {
  if (response == null) {
    print('response is null ');
    return Left(UnknownError());
  } else {
    log('callback : ${callback.toString()}response.statusCode : ${response.statusCode} | response.body ${response.body}');
    try {
      switch (response.statusCode) {
        case 200:
          {
            final Map<String, dynamic> body = json.decode(response.body);
            print("body= $body");
            if (body.containsKey("code")) {
              BaseResponse baseResponse = BaseResponse.fromJson(body);
              print("baseResponse= $baseResponse");
              if (baseResponse.code != 0) {
                if (baseResponse.refreshTokenExpired) {
                  return Left(SessionExpiry(message: baseResponse.message));
                } else if (baseResponse.userResigned) {
                  return Left(UserResigned(message: baseResponse.message));
                }
                return Left(ServerValidation(message: baseResponse.message));
              } else {
                var result = await compute(callback, response.body);
                return Right(result as Q);
              }
            } else {
              return Left(InvalidResponse());
            }
          }
          break;
        case 401:
          return Left(ForbiddenError());
          break;
        case 403:
          return Left(UnAuthorizedError());
          break;
        case 404:
          return Left(ServerError(
              statusCode: response.statusCode, message: "File not found"));
          break;
        case 500:
          return Left(ServerError(
              statusCode: response.statusCode, message: "Server Failure"));
          break;
        default:
          return Left(UnknownError(
              statusCode: response.statusCode, message: response.body));
      }
    } catch (e) {
      // if (kDebugMode) {
      //   throw e;
      // }
      return Left(UnknownError());
    }
  }
4
  • why dont you add condition else if ( response.body["code"] ) ==1 { show alert } Commented May 8, 2024 at 13:30
  • @pmatatias - I want my code to enter the below block, if (body.containsKey("code")) {. How would adding a else part resolve the issue? Commented May 9, 2024 at 5:02
  • As far as I can tell the map response.body has only one entry with key "synchData". That's why body.containsKey("code") is always false. Commented May 9, 2024 at 6:59
  • @DanR- Can you guide me how to access "code" ? Commented May 9, 2024 at 8:23

1 Answer 1

-1

You can access JSON objects using the dart:convert library, which provides functions to encode and decode JSON. Here's a basic guide on how to access JSON objects in Flutter:

import 'dart:convert';

String jsonString = '{"name": "John", "age": 30}'; 
Map<String, dynamic> jsonMap = jsonDecode(jsonString);

Example :


import 'dart:convert';
    
void main() {
  // Example JSON string
  String jsonString = '{"name": "John", "age": 30}';
    
  // Decode JSON string into a Dart object
  Map<String, dynamic> jsonMap = jsonDecode(jsonString);
    
  // Access JSON properties
  String name = jsonMap['name'];
  int age = jsonMap['age'];
    
  // Print the values
  print('Name: $name');
  print('Age: $age');
    
  // Example with JSON array
  String jsonArrayString = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';
    
   // Decode JSON array string into a Dart list
   List<dynamic> jsonArray = jsonDecode(jsonArrayString);
    
   // Access elements of the array
   String firstName = jsonArray[0]['name'];
   int secondAge = jsonArray[1]['age'];
    
   // Print the values
   print('First person: $firstName, Age: $age');
   print('Second person: ${jsonArray[1]['name']}, Age: $secondAge');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.