Home > Back-end >  How can I fix this error Unhandled Exception: type 'String' is not a subtype of type '
How can I fix this error Unhandled Exception: type 'String' is not a subtype of type '

Time:09-23

I tired to make get http request to my server. On postman I get the response successfully but when I tried to do it through the application I get this error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

Please there a way I can resolve this problem I've tried but its not working.

Here's my code :

import 'dart:io';

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

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

class TestApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String data;
  var superheros_length;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  void getData() async {
     int id = 1; 
     var token =
        'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiODU2NDE3YTYwMTFjODFiNTQxYzkzOGY5YWFhNGU1OTY0MzYwYThmZGFiOGMwMGFmMGUwNzIxMTM2MTE5YmY5YjQwZjMyZGFkNjQ4YzdhOTIiLCJpYXQiOjE2MzEzNTQzNDguMDYxOTI5LCJuYmYiOjE2MzEzNTQzNDguMDYxOTM5LCJleHAiOjE2NjI4OTAzNDcuNjk0MDc0LCJzdWIiOiIyIiwic2NvcGVzIjpbXX0.JoGlxB2Htg3t3Fjpmtw6oKnuGXktN4n3g3xWa1Eh0U_TgKKCQv9OB04vaqkcaPo66EYvP89gxKuIIhuGJiEAXdTj0X_ScdNWwvB8Dki_CLQu7_MUyOXakxjz5jSe2xB-xnIB3-y8xc8rOkWZTf6QcPZm1eXUNGWelemvTafIzNm-YeGmpwBaXN2E04QUJ2EYBLu13h7T53rFG3wDBa2j10RS_FWtBlUxgYF5y-3aZNypIzdNI8dqFXuZl_0Crz4MHHFVgchFixJK_txoG2S08jqBCoaUuArFlxqVVL-wcMci6MITPCbiib-_2J4jydqwKgnxzGBqzX6hj0RXdT-BqolvsV5ZGX5sY8ANZR9AvGaJ3SQWbcNv5wVT_DlTqMSfjNwtaOYOocH_LTFNmhjQyTW8TqbiyJHuYbtKRDcwJ2X4kSK-IvA7nyn8xefcempuFYO9M6BD00E-WoiaKwEbxJa3iQsiHgcNziPI-3Lq7S-9CDNHYYiDrgyIrwRhcFuIklmFrsGl8tb08hReNLInlVcy_eAjYifjlJvJYYXdozuhAobcVxkR6z1Xn_N2Vta7OYMWdG4kCYCfR1uF6pypxvlxxoYcwO2Q3Aj3sVPdz03B8gYvmrx-F55qbXwfXdtT3LWUj_ziJOG53GLdDy8DsmKx0c1vDjuLpRz_EPhTYEQ';
  
  String url = 'https://app.pyramidpharmacy.com/api/get-prescriptions-by-user-id';

    http.Response response =
        await http.get(url   '/'   id.toString(),
           headers: {
             "Accept": "application/json",
             "Content-type": "application/json",
              HttpHeaders.authorizationHeader: 'Bearer $token'
             }
          );
        
        // get("https://protocoderspoint.com/jsondata/superheros.json");

    if (response.statusCode == 200) {
      data = response.body; //store response as string

      setState(() {
        superheros_length = jsonDecode(
            data)['id']; //get all the data from json string superheros

        print("Http Response");
        print(superheros_length.length); // just printed length of data
      });

      var venam = jsonDecode(data)[1]['screen_shot_path']; // Just to see if its getting the image

      print(venam);
    } else {
      print(response.statusCode);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Prescription List"),
        backgroundColor: Colors.green,
      ),
      body: ListView.builder(
        itemCount: superheros_length == null ? 0 : superheros_length.length,
        itemBuilder: (BuildContext context, int index) {
          return Card(
            child: ListTile(
              leading: Image.network(
                jsonDecode(data)[index]['screen_shot_path'],
                fit: BoxFit.fill,
                width: 100,
                height: 500,
                alignment: Alignment.center,
              ),
              title: Text(jsonDecode(data)[index]['title']),
              subtitle: Text(jsonDecode(data)[index]['created_at']),
            ),
          );
        },
      ),
    );
  }
}

Below is my response from postman test:

[
    {
        "id": 1,
        "title": "Diabetics Prescription",
        "screen_shot_path": "https://app.pyramidpharmacy.com/public/screenshots/41600.jpg",
        "user_id": "1",
        "status": "Pending",
        "created_at": "2021-08-07T09:49:00.000000Z",
        "updated_at": "2021-09-16T16:07:11.000000Z"
    },
    {
        "id": 8,
        "title": "DIabetics Challenge",
        "screen_shot_path": "https://app.pyramidpharmacy.com/public/screenshots/25635.jpg",
        "user_id": "1",
        "status": "Pending",
        "created_at": "2021-09-16T16:33:01.000000Z",
        "updated_at": "2021-09-16T16:33:02.000000Z"
    },
    {
        "id": 7,
        "title": "DIabetics Challenge",
        "screen_shot_path": "https://app.pyramidpharmacy.com/public/screenshots/16030.jpg",
        "user_id": "1",
        "status": "Pending",
        "created_at": "2021-09-16T16:32:42.000000Z",
        "updated_at": "2021-09-16T16:32:44.000000Z"
    },
    {
        "id": 6,
        "title": "Covid 19",
        "screen_shot_path": "https://app.pyramidpharmacy.com/public/screenshots/43563.jpg",
        "user_id": "1",
        "status": "Pending",
        "created_at": "2021-09-16T16:25:26.000000Z",
        "updated_at": "2021-09-16T16:26:45.000000Z"
    }
]

Any Assistance will greatly help. Thanks.

CodePudding user response:

That's because the returned JSON data is a list of items.

To the best of my knowleadge you cannot directly retrieve all ids via ['id'], it's expecting an index.

You have to iterate through the list like so:

  setState(() {
    List jsonList = jsonDecode(data);

    List ids = [];
    for (int i = 0; i < jsonList.length; i  ) {
      ids.add(jsonList[i]['id']);
    }

    print("Http Response");
    print(ids.length); // just printed length of data
  });

You can also obtain other parts of the JSON in a similar fashion within the loop.

  • Related