Home > Mobile >  My app doesn't recognize data from model file
My app doesn't recognize data from model file

Time:08-14

Hello this is my model file;

// To parse this JSON data, do
//
//     final hisselist = hisselistFromJson(jsonString);

import 'dart:convert';

Hisselist hisselistFromJson(String str) => Hisselist.fromJson(json.decode(str));

String hisselistToJson(Hisselist data) => json.encode(data.toJson());

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

  bool success;
  List<dynamic> result;

  factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist(
    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.rate,
    required this.lastprice,
    required this.lastpricestr,
    required this.hacim,
    required this.hacimstr,
    required this.text,
    required this.code,
  });

  double rate;
  double lastprice;
  String lastpricestr;
  double hacim;
  String hacimstr;
  String text;
  String code;

  factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass(
    rate: json["rate"].toDouble(),
    lastprice: json["lastprice"].toDouble(),
    lastpricestr: json["lastpricestr"],
    hacim: json["hacim"].toDouble(),
    hacimstr: json["hacimstr"],
    text: json["text"],
    code: json["code"],
  );

  Map<String, dynamic> toJson() => {
    "rate": rate,
    "lastprice": lastprice,
    "lastpricestr": lastpricestr,
    "hacim": hacim,
    "hacimstr": hacimstr,
    "text": text,
    "code": code,
  };
}

And this is my file where i call API

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

import '../models/apis/hisselist.dart';

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

  @override
  _StocksState createState() => _StocksState();
}

class _StocksState extends State<Stocks> with AutomaticKeepAliveClientMixin {



  ScrollController? controller;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi');
  var counter;
  var hisseResult;
  Future callHisse() 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 = hisselistFromJson(response.body);
        if(mounted);
        setState(() {
          counter = 200;
          hisseResult = result;
        });
        return result;
      } else {
        print(response.statusCode);
      }
    } catch(e) {
      print(e.toString());
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    callHisse();
  }
  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        automaticallyImplyLeading: false,
        title: Text(
            'Hisseler'
        ).tr(),
      ),
      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(hisseResult.data[index].code),
                    subtitle: Text(hisseResult.data[index].text),
                  ),
                );
          }) : Center(child: CircularProgressIndicator(

          )),
        ),
      ),

    );


  }

  @override
  bool get wantKeepAlive => true;
}

And I'm getting this error? enter image description here

What's wrong with it? Thanks for your help

CodePudding user response:

Hisselist class has only two properties, success and result.

This line of code returns result that is Hisselist type:

var result = hisselistFromJson(response.body);

You should avoid using var type here and set Hisselist instead:

Hisselist? result = hisselistFromJson(response.body);

hisseResult variable is also Hisselist type so you can only use success and result properties, there is no data property defined in Hisselist class.

Hisselist? hisseResult instead od var type.

  title: Text(hisseResult?.result[index].code ?? ""),
  subtitle: Text(hisseResult?.result[index].text ?? ""),

CodePudding user response:

There is no field as it described on your model class I think you want result.

Try var hisseResult; to Hisselist? hisseResult;

title: Text(hisseResult?.result[index].code??""),

CodePudding user response:

hisseResult.result[index] replace for hisseResult.data[index] itemCount: hisseResult.result.length replace for itemCount: counter,

  • Related