I have to Display Specific Item first and then rest all in ListView, So how i can do this.
Json Response is Below.
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "[email protected]",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-image.jpg"
},
{
"id": 8,
"email": "[email protected]",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://reqres.in/img/faces/8-image.jpg"
},
{
"id": 9,
"email": "[email protected]",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://reqres.in/img/faces/9-image.jpg"
},
{
"id": 10,
"email": "[email protected]",
"first_name": "Byron",
"last_name": "Fields",
"avatar": "https://reqres.in/img/faces/10-image.jpg"
},
{
"id": 11,
"email": "[email protected]",
"first_name": "George",
"last_name": "Edwards",
"avatar": "https://reqres.in/img/faces/11-image.jpg"
},
{
"id": 12,
"email": "[email protected]",
"first_name": "Rachel",
"last_name": "Howell",
"avatar": "https://reqres.in/img/faces/12-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}
As above Data suppose i have to display user data first in ListView which id is 10 then after rest all user data.
So how i can do this?
CodePudding user response:
Suppose you parse the data
into User
objects, you probably have access to the user id of the current user and can simply filter the list from there.
List<User> allUsers = [...];
int currentUserId = 10;
// get the specific sets to work with
User currentUser = allUsers.firstWhere((user) => user.id == currentUserId);
List<User> otherUsers = allUsers.where((user) => user.id != currentUserId).toList();
return Column(
children: [
SingleUserView(user: currentUser),
ListView.builder(
itemCount: otherUsers.length,
builder: (context, index) {
User user = otherUsers[index];
return ListUserView(user: user);
}
),
],
);
Which essentially just uses the where
and firstWhere
methods in a List
to filter it accordingly.
Reading your question again, maybe you meant that you want the first item in the ListView
to be the SingleUserView
. That's not too much different and could look like
return ListView.builder(
itemCount: otherUsers.length 1,
builder: (context, index) {
// first item in the ListView is the current user
if (index == 0) return SingleUserView(user: currentUser);
// otherwise build a card for the current one
User user = otherUsers[index - 1];
return ListUserView(user: user);
}
),
);
CodePudding user response:
you could do it in so many ways; you could also manipulate the data array before displaying it, like:
var index = data.indexWhere((d) => d['id'] ==10);
var d = data.removeAt(index);
data.insert(0, d);
You could also build another array and leave the original intact:
var d = data.where((d) => d['id'] ==10).first;
var rest = data.where((d) => d['id'] != 10).toList();
var newdata = [d, …rest];
All in all, I’d advise not to do the logic during the ListView building or even rendering, do it outside, then feed it to the ListView already processed
CodePudding user response:
Here you go:
class Test extends StatefulWidget {
Test({Key? key}) : super(key: key);
@override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
final json = {
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "[email protected]",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-image.jpg"
},
{
"id": 8,
"email": "[email protected]",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://reqres.in/img/faces/8-image.jpg"
},
{
"id": 9,
"email": "[email protected]",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://reqres.in/img/faces/9-image.jpg"
},
{
"id": 10,
"email": "[email protected]",
"first_name": "Byron",
"last_name": "Fields",
"avatar": "https://reqres.in/img/faces/10-image.jpg"
},
{
"id": 11,
"email": "[email protected]",
"first_name": "George",
"last_name": "Edwards",
"avatar": "https://reqres.in/img/faces/11-image.jpg"
},
{
"id": 12,
"email": "[email protected]",
"first_name": "Rachel",
"last_name": "Howell",
"avatar": "https://reqres.in/img/faces/12-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text":
"To keep ReqRes free, contributions towards server costs are appreciated!"
}
};
List<Model> parsedList = [];
List<Model> newList = [];
@override
void initState() {
super.initState();
parsedList = (json["data"] as List).map((e) => Model.fromMap(e)).toList();
final index = parsedList.indexWhere((element) => element.id == 10);
newList = [parsedList.removeAt(index), ...parsedList];
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: newList.length,
itemBuilder: (ctx, index) => Text(newList[index].first_name),
),
);
}
}
class Model {
final int id;
final String email;
final String first_name;
final String last_name;
final String avatar;
Model(this.id, this.email, this.first_name, this.last_name, this.avatar);
Map<String, dynamic> toMap() {
return {
'id': id,
'email': email,
'first_name': first_name,
'last_name': last_name,
'avatar': avatar,
};
}
factory Model.fromMap(Map<String, dynamic> map) {
return Model(
map['id'] ?? 0,
map['email'] ?? '',
map['first_name'] ?? '',
map['last_name'] ?? '',
map['avatar'] ?? '',
);
}
String toJson() => json.encode(toMap());
factory Model.fromJson(String source) => Model.fromMap(json.decode(source));
}
CodePudding user response:
var specifieditem=10;
fetChdata() {
var st =
'{ "page": 2, "per_page": 6, "total": 12, "total_pages": 2, "data": [ { "id": 7, "email": "[email protected]", "first_name": "Michael", "last_name": "Lawson", "avatar": "https://reqres.in/img/faces/7-image.jpg" }, { "id": 8, "email": "[email protected]", "first_name": "Lindsay", "last_name": "Ferguson", "avatar": "https://reqres.in/img/faces/8-image.jpg" }, { "id": 9, "email": "[email protected]", "first_name": "Tobias", "last_name": "Funke", "avatar": "https://reqres.in/img/faces/9-image.jpg" }, { "id": 10, "email": "[email protected]", "first_name": "Byron", "last_name": "Fields", "avatar": "https://reqres.in/img/faces/10-image.jpg" }, { "id": 11, "email": "[email protected]", "first_name": "George", "last_name": "Edwards", "avatar": "https://reqres.in/img/faces/11-image.jpg" }, { "id": 12, "email": "[email protected]", "first_name": "Rachel", "last_name": "Howell", "avatar": "https://reqres.in/img/faces/12-image.jpg" } ], "support": { "url": "https://reqres.in/#support-heading", "text": "To keep ReqRes free, contributions towards server costs are appreciated!" } }';
var m = MainModel.fromJson(json.decode(st));
//here we ordering equal 10 member list if unique get one other wise it may be list
var v10 = m.data!.where((element) => element.id == specifieditem).toList();
//here get non
var n10 = m.data!.where((element) => element.id != specifieditem).toList();
// we summ both list
data = v10 n10;
}
Here we create simple Model class for easy managing you can use json.decode()
to decode to map<string,dynamic>
and customize order
class MainModel {
int? page;
int? perPage;
int? total;
int? totalPages;
List<Data>? data;
Support? support;
MainModel(
{this.page,
this.perPage,
this.total,
this.totalPages,
this.data,
this.support});
MainModel.fromJson(Map<String, dynamic> json) {
page = json['page'];
perPage = json['per_page'];
total = json['total'];
totalPages = json['total_pages'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(new Data.fromJson(v));
});
}
support =
json['support'] != null ? new Support.fromJson(json['support']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['page'] = this.page;
data['per_page'] = this.perPage;
data['total'] = this.total;
data['total_pages'] = this.totalPages;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
if (this.support != null) {
data['support'] = this.support!.toJson();
}
return data;
}
}
class Data {
int? id;
String? email;
String? firstName;
String? lastName;
String? avatar;
Data({this.id, this.email, this.firstName, this.lastName, this.avatar});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
email = json['email'];
firstName = json['first_name'];
lastName = json['last_name'];
avatar = json['avatar'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['email'] = this.email;
data['first_name'] = this.firstName;
data['last_name'] = this.lastName;
data['avatar'] = this.avatar;
return data;
}
}
class Support {
String? url;
String? text;
Support({this.url, this.text});
Support.fromJson(Map<String, dynamic> json) {
url = json['url'];
text = json['text'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
data['text'] = this.text;
return data;
}
}
Here we use future builder
widget for fetching from api and ordering if bulkdata for async
FutureBuilder(
future: fetChdata(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Container(
height: 10,
width: 10,
child: CircularProgressIndicator()));
} else {
var data2 = data[index];
return ListTile(
title: Row(
children: [
Text(
data2.id.toString(),
style: TextStyle(fontSize: 25),
),
Expanded(
child: Align(
alignment: Alignment.topRight,
child: Text(data2.firstName.toString()
data2.lastName.toString()),
)),
],
),
subtitle: Row(
children: [
Expanded(
child: Align(
alignment: Alignment.topRight,
child: Text(data2.email.toString())),
)
],
),
leading: CircleAvatar(
backgroundImage:
NetworkImage(data2.avatar.toString()),
),
);
}
});
})
sample code dartpad
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),
);
}
List<Data> data = [];
fetChdata() {
var st =
'{ "page": 2, "per_page": 6, "total": 12, "total_pages": 2, "data": [ { "id": 7, "email": "[email protected]", "first_name": "Michael", "last_name": "Lawson", "avatar": "https://reqres.in/img/faces/7-image.jpg" }, { "id": 8, "email": "[email protected]", "first_name": "Lindsay", "last_name": "Ferguson", "avatar": "https://reqres.in/img/faces/8-image.jpg" }, { "id": 9, "email": "[email protected]", "first_name": "Tobias", "last_name": "Funke", "avatar": "https://reqres.in/img/faces/9-image.jpg" }, { "id": 10, "email": "[email protected]", "first_name": "Byron", "last_name": "Fields", "avatar": "https://reqres.in/img/faces/10-image.jpg" }, { "id": 11, "email": "[email protected]", "first_name": "George", "last_name": "Edwards", "avatar": "https://reqres.in/img/faces/11-image.jpg" }, { "id": 12, "email": "[email protected]", "first_name": "Rachel", "last_name": "Howell", "avatar": "https://reqres.in/img/faces/12-image.jpg" } ], "support": { "url": "https://reqres.in/#support-heading", "text": "To keep ReqRes free, contributions towards server costs are appreciated!" } }';
var m = MainModel.fromJson(json.decode(st));
var v10 = m.data!.where((element) => element.id == 10).toList();
var n10 = m.data!.where((element) => element.id != 10).toList();
data = v10 n10;
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var widgets = [];
var _mycontroller = ScrollController();
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
// backgroundColor: Colors.transparent,
// bottomNavigationBar: ,
appBar: AppBar(
title: Text("Ordering"),
),
//============
body: FutureBuilder(
future: fetChdata(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Container(
height: 10,
width: 10,
child: CircularProgressIndicator()));
} else {
var data2 = data[index];
return ListTile(
title: Row(
children: [
Text(
data2.id.toString(),
style: TextStyle(fontSize: 25),
),
Expanded(
child: Align(
alignment: Alignment.topRight,
child: Text(data2.firstName.toString()
data2.lastName.toString()),
)),
],
),
subtitle: Row(
children: [
Expanded(
child: Align(
alignment: Alignment.topRight,
child: Text(data2.email.toString())),
)
],
),
leading: CircleAvatar(
backgroundImage:
NetworkImage(data2.avatar.toString()),
),
);
}
});
})),
);
}
}
class MainModel {
int? page;
int? perPage;
int? total;
int? totalPages;
List<Data>? data;
Support? support;
MainModel(
{this.page,
this.perPage,
this.total,
this.totalPages,
this.data,
this.support});
MainModel.fromJson(Map<String, dynamic> json) {
page = json['page'];
perPage = json['per_page'];
total = json['total'];
totalPages = json['total_pages'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(new Data.fromJson(v));
});
}
support =
json['support'] != null ? new Support.fromJson(json['support']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['page'] = this.page;
data['per_page'] = this.perPage;
data['total'] = this.total;
data['total_pages'] = this.totalPages;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
if (this.support != null) {
data['support'] = this.support!.toJson();
}
return data;
}
}
class Data {
int? id;
String? email;
String? firstName;
String? lastName;
String? avatar;
Data({this.id, this.email, this.firstName, this.lastName, this.avatar});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
email = json['email'];
firstName = json['first_name'];
lastName = json['last_name'];
avatar = json['avatar'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['email'] = this.email;
data['first_name'] = this.firstName;
data['last_name'] = this.lastName;
data['avatar'] = this.avatar;
return data;
}
}
class Support {
String? url;
String? text;
Support({this.url, this.text});
Support.fromJson(Map<String, dynamic> json) {
url = json['url'];
text = json['text'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
data['text'] = this.text;
return data;
}
}