Home > Enterprise >  Flutter Unhandled Exception:type'_InternalLinkedHashMap<String,dynamic>' is not a su
Flutter Unhandled Exception:type'_InternalLinkedHashMap<String,dynamic>' is not a su

Time:08-28

im tryin to display data from json api inside my flutter app , My Error :

E/flutter ( 2248): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

My Method:

Future<void> _fetchDataAkhbarGbeli() async {
    const apiUrl = 'data screen below';
    HttpClient client = HttpClient();
    client.autoUncompress = true;
        final HttpClientRequest request = await client.getUrl(Uri.parse(apiUrl));
    request.headers
        .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
    final HttpClientResponse response = await request.close();
        final String content = await response.transform(utf8.decoder).join();
    final List data = json.decode(content);
        setState(() {
      _loadedAkhbarGbeli = data as List;
    });
  }

View:

 Expanded(
                child:ListView.builder(
                  scrollDirection: Axis.vertical,
                  itemCount: _loadedAkhbarGbeli.length,
                  itemBuilder:(BuildContext ctx, index) {
                      return ListTile(
                        title: Text(_loadedAkhbarGbeli[index]["gbeli"]["title"]),
                      );
                    },
                    )
                )

screen

how can i solve this problem, Thanks

CodePudding user response:

The content is actually a map. You can get list directly like

 final List? data = json.decode(content)["gbeli"] as List?;

Now on use case it will

Text("${_loadedAkhbarGbeli[index]["title"]}")

CodePudding user response:

first create a model like this:

class News {
  final String title;
  final String description;

  News({@required this.title,@required this.description});
  
static List<News> fromJson(Map<String, Object> _json) {
    List<News> result = [];
    for (var item in _json['gbeli']) {
      var news = News(
          title: item['title'] as String,
          description: item['description'] as String ?? '',
          
      );
      result.add(permission);
      
    }
    return result;
  }
}

and use it like this:

 _loadedAkhbarGbeli = News.fromJson(json.decode(content));

and after that in your listview use it like this:

ListTile(
    title: Text(_loadedAkhbarGbeli[index].title),
)
  • Related