Hello 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 xxxx'
};
final response = await http.get(url,headers:requestHeaders);
if(response.statusCode == 200){
var result = hisselistFromJson(response.body);
if(mounted);
setState(() {
counter = result.result.length;
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) => SizedBox(
height: 2,
),
itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(hisseResult?.result[index].lastpricestr.toString()??""),
subtitle: Text(hisseResult?.result[index].text??""),
),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
}
I want to sort stocks with their name alphabetically. how can I do this? Thanks for your help
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<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!;
}
}
CodePudding user response:
You need to do a sort function before you return the hisseResult like so:
Assuming you get a json or class object in a list like this:
//SAMPLE LIST
List<Map> result= [
{"text": 'B', "lastprice": 10},
{"text": 'Y', "lastprice": 10},
{"text": '2', "lastprice": 10},
{"text": 'X', "lastprice": 10},
{"text": 'A', "lastprice": 10},
{"text": '1', "lastprice": 10}
];
in your function callHisse(), do a sort like this:
counter = result.length;
result.sort((a, b) => a["text"].compareTo(b["text"]));
hisseResult = result;
This sorts alphabetically and numerically.
This is a related post: Sort a list of maps in Dart - Second Level Sort in Dart And the official docs.: https://api.flutter.dev/flutter/dart-core/List/sort.html
Hope it helps.
CodePudding user response:
You can use the sort() method of the dart List to sort a list lexicographically (alphabetically).
Let's assume you have a list i.e.
List<Model> list = [
Model(name: xyz, id: 1),
Model(name: abc, id: 2),
Model(name: mno, id: 3),
];
we want to sort the list using "name" alphabetically. So for that, we have to take this step.
var sortedList = list.sort((model1, model2) => {
model1.name.compareTo(model2.name);
});
Here the sortedList is the list that you want to show.