Home > front end >  error: The operator '[]' isn't defined for the type 'Haberler'. flutter
error: The operator '[]' isn't defined for the type 'Haberler'. flutter

Time:08-19

i converted XML to api from a service: this is my model :

// To parse this JSON data, do
//
//     final economylistXml = economylistXmlFromJson(jsonString);

import 'dart:convert';

EconomylistXml economylistXmlFromJson(String str) => EconomylistXml.fromJson(json.decode(str));

String economylistXmlToJson(EconomylistXml data) => json.encode(data.toJson());

class EconomylistXml {
  EconomylistXml({
    required this.haberler,
  });

  Haberler haberler;

  factory EconomylistXml.fromJson(Map<String, dynamic> json) => EconomylistXml(
    haberler: Haberler.fromJson(json["haberler"]),
  );

  Map<String, dynamic> toJson() => {
    "haberler": haberler.toJson(),
  };
}

class Haberler {
  Haberler({
    required this.haber,
  });

  List<Haber> haber;

  factory Haberler.fromJson(Map<String, dynamic> json) => Haberler(
    haber: List<Haber>.from(json["haber"].map((x) => Haber.fromJson(x))),
  );

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

class Haber {
  Haber({
    required this.haberManset,
    required this.haberResim,
    required this.haberLink,
    required this.haberId,
    required this.haberVideo,
    required this.haberAciklama,
    required this.haberMetni,
    required this.haberKategorisi,
    required this.haberTarihi,
    required this.mansetResim,
    required this.izlesId,
    required this.yorumSay,
    required this.okunmaadedi,
    required this.anasayfamanset,
    required this.kategorimanset,
  });

  String haberManset;
  String haberResim;
  String haberLink;
  String haberId;
  String haberVideo;
  String haberAciklama;
  String haberMetni;
  HaberKategorisi? haberKategorisi;
  String haberTarihi;
  String mansetResim;
  String izlesId;
  String yorumSay;
  String okunmaadedi;
  String anasayfamanset;
  String kategorimanset;

  factory Haber.fromJson(Map<String, dynamic> json) => Haber(
    haberManset: json["haber_manset"],
    haberResim: json["haber_resim"],
    haberLink: json["haber_link"],
    haberId: json["haber_id"],
    haberVideo: json["haber_video"],
    haberAciklama: json["haber_aciklama"],
    haberMetni: json["haber_metni"],
    haberKategorisi: haberKategorisiValues.map[json["haber_kategorisi"]],
    haberTarihi: json["haber_tarihi"],
    mansetResim: json["manset_resim"],
    izlesId: json["izles_id"],
    yorumSay: json["yorumSay"],
    okunmaadedi: json["okunmaadedi"],
    anasayfamanset: json["anasayfamanset"],
    kategorimanset: json["kategorimanset"],
  );

  Map<String, dynamic> toJson() => {
    "haber_manset": haberManset,
    "haber_resim": haberResim,
    "haber_link": haberLink,
    "haber_id": haberId,
    "haber_video": haberVideo,
    "haber_aciklama": haberAciklama,
    "haber_metni": haberMetni,
    "haber_kategorisi": haberKategorisiValues.reverse[haberKategorisi],
    "haber_tarihi": haberTarihi,
    "manset_resim": mansetResim,
    "izles_id": izlesId,
    "yorumSay": yorumSay,
    "okunmaadedi": okunmaadedi,
    "anasayfamanset": anasayfamanset,
    "kategorimanset": kategorimanset,
  };
}

enum HaberKategorisi { EKONOMI, DNYA }

final haberKategorisiValues = EnumValues({
  "Dünya": HaberKategorisi.DNYA,
  "Ekonomi": HaberKategorisi.EKONOMI
});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String>? reverseMap;

  EnumValues ( this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap!;
  }
}

And this is my file where i call api

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

import '../models/apis/economy_xml.dart';
import 'haberdetail.dart';


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

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

class _EconomyState extends State<Economy> {
  ScrollController? controller;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final url = Uri.parse('https://v1.nocodeapi.com/miktadtahir/xml_to_json/htvLvoPDCwIEyTxa?url=https://www.trthaber.com/xml_mobile.php?tur=xml_genel&kategori=ekonomi&adet=20&selectEx=yorumSay,okunmaadedi,anasayfamanset,kategorimanset');
  var counter;
  EconomylistXml? haberResult;

  Future callHaber() async {
    try{

      final response = await http.get(url);

      if(response.statusCode == 200){
        var haberler = economylistXmlFromJson(response.body);

        if(mounted);
        setState(() {
          haberResult = haberler;
        });
        return haberler;
      } 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(
            'Ekonomi Haberleri'
        ),
      ),
      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?.haberler[index].haberManset??""),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(haberResult?.haberler[index].haberResim??""),),


                    onTap: () => Navigator.push(
                      context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.haberler[index].haberMetni??"", title: haberResult?.haberler[index].haberManset??"",image: haberResult?.haberler[index].haberResim??"")),),
                  ),
                );
              }) : Center(child: CircularProgressIndicator(

          )),
        ),
      ),
    );

  }
}

I'm getting errors where i call datas from model : error: The operator '[]' isn't defined for the type 'Haberler'. ı get this error on these lines

                  child: ListTile(
                    title: Text(haberResult?.haberler[index].haberManset??""),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(haberResult?.haberler[index].haberResim??""),),


                    onTap: () => Navigator.push(
                      context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.haberler[index].haberMetni??"", title: haberResult?.haberler[index].haberManset??"",image: haberResult?.haberler[index].haberResim??"")),),
                  ),

how can i fix this? Thanks for your help

CodePudding user response:

Add .haber after .haberler Because Haberler is not a list, Haber is a list so you can access index from haber.

   child: ListTile(
                title: Text(haberResult?.haberler.haber[index].haberManset??""),
                leading: CircleAvatar(
                  backgroundImage: NetworkImage(haberResult?.haberler.haber[index].haberResim??""),),


                onTap: () => Navigator.push(
                  context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.haberler.haber[index].haberMetni??"", title: haberResult?.haberler.haber[index].haberManset??"",image: haberResult?.haberler.haber[index].haberResim??"")),),
              ),
  • Related