Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Raw json from GraphQL Flutter

I want to get raw json data from GraphQL flutter.

here is part of the data I want to get:

{
  "data": {
    "countries": [
      {
        "name": "Andorra",
        "code": "AD",
        "native": "Andorra",
        "phone": "376"
      },
      {
        "name": "United Arab Emirates",
        "code": "AE",
        "native": "دولة الإمارات العربية المتحدة",
        "phone": "971"
      },

but this is the result that GraphQL returns to me:

{__typename: Query,
 countries: [{__typename: Country, name: Andorra, code: AD, native: Andorra, phone: 376}, 
{__typename: Country, name: United Arab Emirates,
 code: AE, native: دولة الإمارات العربية المتحدة, phone: 971},

the format is all wrong...

and this is my code:

  void getCountryName() async {
    pageState(AppState.loading);

    String q = """
{
  countries {
    name
    code
    native
    phone
  }
}
""";
    QueryResult res = await countriesClient.query(
      QueryOptions(
        document: gql(q),
        optimisticResult: Country,
        fetchPolicy: FetchPolicy.networkOnly,
      ),
    );

  }

print(res.data);
like image 396
SinaMN75 Avatar asked Sep 08 '25 04:09

SinaMN75


1 Answers

it has been a while since you posted this question. but i am gonna provide an answer.

The __typename fields are automatically added by the GraphQL client to help with caching and type checking, but you can filter them out if you don't need them.

In your code, when query is successfully executed you can use the following code to extract the raw data from res variable.

/// check if there is any exception in the response
if (res.hasException) {
    print('Error: ${res.exception.toString()}');
/// i am assuming you have some error state 
    pageState(AppState.error);
    return;
  }

  /// Extract the countries data from response
  final List countries = res.data?['countries'] ?? [];

  /// Print the extracted data
  print(countries);

/// you can call fromJson method of model here..

this should solve your problem.

like image 80
IKRAM UL HAQ Avatar answered Sep 10 '25 12:09

IKRAM UL HAQ