flutterapirestdart-null-safetynull-safety

Class '_InternalLinkedHashMap<String, dynamic>' has no instance getter 'name'. Receiver: _LinkedHashMap len:7 Tried calling: name Flutter


im trying to call an api. This is model :

// To parse this JSON data, do
//
//     final economylist = economylistFromJson(jsonString);

import 'dart:convert';

Economylist economylistFromJson(String str) => Economylist.fromJson(json.decode(str));

String economylistToJson(Economylist data) => json.encode(data.toJson());

class Economylist {
  Economylist({
    required this.success,
    required this.result,
  });

  bool success;
  List<dynamic> result;

  factory Economylist.fromJson(Map<String, dynamic> json) => Economylist(
    success: json["success"],
    result: List<dynamic>.from(json["result"].map((x) => x)),
  );

  Map<String, dynamic> toJson() => {
    "success": success,
    "result": List<dynamic>.from(result.map((x) => x)),
  };
}

class ResultClass {
  ResultClass({
    required this.key,
    required this.url,
    required this.description,
    required this.image,
    required this.name,
    required this.source,
  });

  String key;
  String url;
  String description;
  String image;
  String name;
  String source;

  factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass(
    key: json["key"],
    url: json["url"],
    description: json["description"],
    image: json["image"],
    name: json["name"],
    source: json["source"],
  );

  Map<String, dynamic> toJson() => {
  "key": key,
  "url": url,
  "description": description,
  "image": image,
  "name": name,
  "source": source,
  };
}

This is my file where i call api

import 'package:flutter/material.dart';
import 'package:halkaarzhisseler/models/apis/economy_api.dart';
import 'package:http/http.dart' as http;




class Economy extends StatefulWidget {
  const Economy({Key? key}) : super(key: key);

  @override
  State<Economy> createState() => _EconomyState();
}

class _EconomyState extends State<Economy> {

  final scaffoldKey = GlobalKey<ScaffoldState>();
  final url = Uri.parse('https://api.collectapi.com/news/getNews?country=tr&tag=economy');
  var counter;
  Economylist? haberResult;

  Future callHaber() async {
    try{
      Map<String, String> requestHeaders = {
        'Content-Type': 'application/json',
        'Authorization': 'apikey xxx'
      };
      final response = await http.get(url,headers:requestHeaders);

      if(response.statusCode == 200){
        var result = economylistFromJson(response.body);

        if(mounted);
        setState(() {
          counter = result.result.length;
          haberResult = result;
        });
        return result;
      } else {
        print(response.statusCode);
      }
    } catch(e) {
      print(e.toString());
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    callHaber();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        automaticallyImplyLeading: false,
        title: Text(
            'Hisseler'
        ),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: counter != null ?

          ListView.builder(
              itemCount: counter,
              itemBuilder: (context, index){
                return Card(
                  child: ListTile(
                    title: Text(haberResult?.result[index].name??""),
                    subtitle: Text(haberResult?.result[index].source??""),                  ),
                );
              }) : Center(child: CircularProgressIndicator(

          )),
        ),
      ),
    );

  }
}
This is the error i get : enter image description here

I think im making some mistake when im calling the api about Future but i couldnt fix it. How can i fix this? thanks for your help


Solution

  • You need to change result property of Economylist class to List. use this model class:

    class Economylist {
      Economylist({
        required this.success,
        required this.result,
      });
    
      bool success;
      List<ResultClass> result;
    
      factory Economylist.fromJson(Map<String, dynamic> json) => Economylist(
        success: json["success"],
        result: json["result"].map<ResultClass>((x) => ResultClass.fromJson(x)).toList(),
      );
    
      Map<String, dynamic> toJson() => {
        "success": success,
        "result": result.map((x) => x.toJson()),
      };
    }