Home > front end >  type 'Null' is not a subtype of type 'String' flutter on api call
type 'Null' is not a subtype of type 'String' flutter on api call

Time:08-19

Im using a service to create api from xml. This is my model file:

// 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 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;

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.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??"")),),
                  ),
                );
              }) : Center(child: CircularProgressIndicator(

          )),
        ),
      ),
    );

  }
}



/*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://api.collectapi.com/news/getNews?country=tr&tag=economy&padding=10');
  var counter;
  Economylist? haberResult;

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

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

        if(mounted);
        setState(() {
          counter = 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(
            '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?.result[index].name??""),
                leading: CircleAvatar(
                backgroundImage: NetworkImage(haberResult?.result[index].image??""),),


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

          )),
        ),
      ),
    );

  }
}

 */
I'm getting this error on console : type 'Null' is not a subtype of type 'String' and CircularProgressIndicator working continuously. How can i fix this? Thanks for your help

CodePudding user response:

The handle null value it is better to make variable nullable data on entities

class Haber {
  String? haberManset;
  String? haberResim;
  String? haberLink;

Or provide empty string on null case while reading JSON

  haberVideo: json["haber_video"]??"", //this
  izlesId: json["izles_id"]??"",

CodePudding user response:

You can make response != null to the top. And check the debug console for the response. Probably you get some other exception like socket exception.

 try{

      final response = await http.get(url);
if(response != null){ //this line you need to add
 if(response.statusCode == 200){
        var haberler = economylistXmlFromJson(response.body);

        if(mounted);
        setState(() {
          haberResult = haberler;
        });
        return haberler;
      } else {
        print(response.statusCode);
      }
}else{
//stop indicator in here if response is null
//you're code in here
}
      
    } catch(e) {
      print(e.toString());
    }

I hope this helps

CodePudding user response:

Change String to String? at not required fields:

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; //<-- here
  String haberAciklama;
  String haberMetni;
  HaberKategorisi? haberKategorisi;
  String haberTarihi;
  String mansetResim;
  String? izlesId; //<-- and here
  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,
  };
}

  • Related