1

/*
// 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<ResultClass> result;

  factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist(
    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()),
  };
}

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: double.tryParse(json["rate"].toString()) ?? 0.0,
    lastprice: double.tryParse(json["lastprice"].toString()) ?? 0.0,
    lastpricestr: json["lastpricestr"],
    hacim: double.tryParse(json["hacim"].toString()) ?? 0.0,
    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,
  };
}


 */

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

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

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

class Result {
  Result({
    this.rate,
    this.lastprice,
    this.lastpricestr,
    this.hacim,
    this.hacimstr,
    this.min,
    this.minstr,
    this.max,
    this.maxstr,
    this.time,
    this.text,
    this.code,
  });

  double? rate;
  double? lastprice;
  String? lastpricestr;
  String? hacim;
  String? hacimstr;
  dynamic min;
  String? minstr;
  dynamic max;
  String? maxstr;
  Time? time;
  String? text;
  String? code;

  factory Result.fromJson(Map<String, dynamic> json) => Result(
    rate: json["rate"].toDouble(),
    lastprice: json["lastprice"].toDouble(),
    lastpricestr: json["lastpricestr"],
    hacim: json["hacim"],
    hacimstr: json["hacimstr"],
    min: json["min"],
    minstr: json["minstr"],
    max: json["max"],
    maxstr: json["maxstr"],
    time: timeValues.map[json["time"]],
    text: json["text"],
    code: json["code"],
  );

  Map<String, dynamic> toJson() => {
    "rate": rate,
    "lastprice": lastprice,
    "lastpricestr": lastpricestr,
    "hacim": hacim,
    "hacimstr": hacimstr,
    "min": min,
    "minstr": minstr,
    "max": max,
    "maxstr": maxstr,
    "time": timeValues.reverse[time],
    "text": text,
    "code": code,
  };
}

enum Time { THE_1809, THE_1808, THE_1805, THE_1810, THE_1759, THE_1755 }

final timeValues = EnumValues({
  "17:55": Time.THE_1755,
  "17:59": Time.THE_1759,
  "18:05": Time.THE_1805,
  "18:08": Time.THE_1808,
  "18:09": Time.THE_1809,
  "18:10": Time.THE_1810
});

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 where i call api :

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




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

  @override
  State<Hisseler> createState() => _HisselerState();
}

class _HisselerState extends State<Hisseler> {

  final scaffoldKey = GlobalKey<ScaffoldState>();
  final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi');
  var counter;

  Hisselist? hisseResult;

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

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

        if(mounted);
        setState(() {

          counter = result.result.length;
          result.result.sort((a, b) => (a.text ?? "").compareTo(b.text ?? ""));

          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) {
    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.separated(

              itemCount: counter,

              separatorBuilder: (context, index) {
                return Divider(color: Colors.grey[400]);
              },
              itemBuilder: (context, index){
                return Card(
                  child: ListTile(
                    contentPadding: EdgeInsets.all(10),
                    title: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(hisseResult?.result[index].code??"", style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500)),
                        Text(hisseResult?.result[index].text??"",style: TextStyle(color: Colors.grey[500], fontSize: 14))
                      ],
                    ),
                    trailing: Column(
                      children: <Widget>[
                        Text(hisseResult?.result[index].lastpricestr??"", style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500)),
                        Container(
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(5),
                                color: Colors.red
                            ),
                            width: 75,
                            height: 25,
                            child: Text(hisseResult?.result[index].rate.toString()??"",style: TextStyle(color: Colors.white))
                        )
                      ],
                    ),
                ),);
              }) : Center(child: CircularProgressIndicator(

          )),
        ),
      ),
    );
  }
}
This is the result i get: enter image description here

as you see here, code response start with "https:" i don't want to show this "https:" part from response. How i can fix this? Thanks for your help

3
  • You can try to use: api.flutter.dev/flutter/dart-core/String/replaceAll.html Commented Aug 22, 2022 at 0:25
  • @MendelG I can also use substring but I couldn't manage to do it. Can you show me a code example, please? Commented Aug 22, 2022 at 0:28
  • What line of your code is responsible for printing the "https"? Commented Aug 22, 2022 at 0:32

2 Answers 2

1

seems the "https:" comes emberded in your API data, therefore we need to replace that string from the variable code.

Replace the Text code with this:

Text((hisseResult?.result[index].code ?? "")
                    .replaceAll("https:", ""),
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 16,
                    fontWeight: FontWeight.w500))
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain me please why hisseResult?.result[index].code??"".substring(6) is not working?
.substring(index) depends on the length of your string, if your string is less than the index, then you get an error. To use it you need to chech the length of the string first, then get the subtring. It is easier to just replace the string you dont want, because it works if it exists or not.
0

Try this:

hisseResult?.result[index].code?.substring(5)

null safety fix also added

  • subString changed into substring

2 Comments

to use substring we must check the length of the string first, that's why substring not working here. Check the answer of Allan Mitre. If you add a check to the length of the string to this answer, it will be also a correct answer. But using replace is more logical it seems
If you add ? before substring, there is no error and it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.