When I'm trying to remove items from the listview using provider it removed last element from the list.

31 views
Skip to first unread message

sumit kumawat

unread,
Aug 3, 2020, 2:32:08 AM8/3/20
to Flutter Development (flutter-dev)

Hello guys,
When i'm try to remove item(like 0 index item) from this listview using provider it removed the last item from the list. while i'm deleting last element from the list successfully remove last item.
I'm bit confusing why this kind of shit happen with me.
Please help me to figure out this issue.

Also demonstrate on this video what issue is happening
Link:https://drive.google.com/file/d/1UYl8Z7vEj_tZCaYzqe0VqZL2iMla5nIZ/view?usp=sharing

---------------------------------------Modal class with changenotifier------------------
class BandRequestModal with ChangeNotifier {
bool status;
String message;
List data;

BandRequestModal({this.status, this.message, this.data});

BandRequestModal.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
if (json['data'] != null) {
data = new List();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}

List _items=[];

List get item
{
return [..._items];
}
static Map<String, dynamic> servererrorresponse = {
'status': true,
'message': Constants.servererror
};
Future getBandRequestList() async{
List bandrequestList;
String token = await CustomPreferences.getpreferences('token');
Map<String, String> requestHeaders;
if (token.isNotEmpty) {
requestHeaders = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
};
} else {
requestHeaders = {
'Accept': 'application/json',
};
}
try {
final response =
await http.post(Connection.url + 'all-place-request', headers: requestHeaders);
if (response.statusCode == 200) {
Map<String, dynamic> responseJson = json.decode(response.body);
var res = responseJson['data'] as List;
bandrequestList = res
.map((json) => Data.fromJson(json))
.toList();
print("List Size: ${bandrequestList.toString()}");
_items=bandrequestList;
notifyListeners();
return BandRequestModal.fromJson(responseJson);

  } /*else if (response.statusCode == 500) {
    return servererrorresponse;
  }*/
} catch (exception) {
  throw exception;
}

}

Future acceptdeclinerequest(String requestStatus,int requestId) async{
String token = await CustomPreferences.getpreferences('token');
Map<String, String> requestHeaders;
if (token.isNotEmpty) {
requestHeaders = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
};
} else {
requestHeaders = {
'Accept': 'application/json',
};
}
var reqdata = {
"request_id":requestId.toString(),
"status":requestStatus
};
print('accept request data is $reqdata');
try
{
final response =
await http.post(Connection.url + 'respond-place-request', headers: requestHeaders,body: reqdata);
if (response.statusCode == 200) {
Map<String, dynamic> responseJson = json.decode(response.body);
final existingProductIndex = _items.indexWhere((prod) => prod.id == requestId);
var existingProduct = _items[existingProductIndex];
_items.removeAt(existingProductIndex);
notifyListeners();
return servererrorresponse;
// } /*else if (response.statusCode == 500) {
return servererrorresponse;
}
} catch (exception) {
throw exception;
}
}

}

class Data {
int id;
int bandId;
int placeId;
int status;
int requestStatus;
String updatedAt;
String createdAt;
BandDetails bandDetails;
PlaceDetails placeDetails;

Data(
{this.id,
this.bandId,
this.placeId,
this.status,
this.requestStatus,
this.updatedAt,
this.createdAt,
this.bandDetails,
this.placeDetails});

Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
bandId = json['band_id'];
placeId = json['place_id'];
status = json['status'];
requestStatus = json['request_status'];
updatedAt = json['updated_at'];
createdAt = json['created_at'];
bandDetails = json['band_details'] != null
? new BandDetails.fromJson(json['band_details'])
: null;
placeDetails = json['place_details'] != null
? new PlaceDetails.fromJson(json['place_details'])
: null;
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['band_id'] = this.bandId;
data['place_id'] = this.placeId;
data['status'] = this.status;
data['request_status'] = this.requestStatus;
data['updated_at'] = this.updatedAt;
data['created_at'] = this.createdAt;
if (this.bandDetails != null) {
data['band_details'] = this.bandDetails.toJson();
}
if (this.placeDetails != null) {
data['place_details'] = this.placeDetails.toJson();
}
return data;
}
}

class BandDetails {
int id;
String name;
String username;
String bandName;
String bandPic;
String email;
String emailVerifiedAt;
String userType;
String profileImage;
String referredById;
int status;
String forgotToken;
String code;
String registrationType;
String uniqueCode;
int toggleNotification;
int isFavourite;
String createdAt;
String updatedAt;

BandDetails(
{this.id,
this.name,
this.username,
this.bandName,
this.bandPic,
this.email,
this.emailVerifiedAt,
this.userType,
this.profileImage,
this.referredById,
this.status,
this.forgotToken,
this.code,
this.registrationType,
this.uniqueCode,
this.toggleNotification,
this.isFavourite,
this.createdAt,
this.updatedAt});

BandDetails.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
username = json['username'];
bandName = json['band_name'];
bandPic = json['band_pic'];
email = json['email'];
emailVerifiedAt = json['email_verified_at'];
userType = json['user_type'];
profileImage = json['profile_image'];
referredById = json['referred_by_id'];
status = json['status'];
forgotToken = json['forgot_token'];
code = json['code'];
registrationType = json['registration_type'];
uniqueCode = json['unique_code'];
toggleNotification = json['toggle_notification'];
isFavourite = json['is_favourite'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['username'] = this.username;
data['band_name'] = this.bandName;
data['band_pic'] = this.bandPic;
data['email'] = this.email;
data['email_verified_at'] = this.emailVerifiedAt;
data['user_type'] = this.userType;
data['profile_image'] = this.profileImage;
data['referred_by_id'] = this.referredById;
data['status'] = this.status;
data['forgot_token'] = this.forgotToken;
data['code'] = this.code;
data['registration_type'] = this.registrationType;
data['unique_code'] = this.uniqueCode;
data['toggle_notification'] = this.toggleNotification;
data['is_favourite'] = this.isFavourite;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}

class PlaceDetails {
int id;
String name;
String email;
String password;
String address;
String addressLat;
String addressLong;
String image;
String mobile;
String parking;
String ownerName;
String token;
int status;
int emailVerify;
int requestStatus;
String createdAt;
String updatedAt;

PlaceDetails(
{this.id,
this.name,
this.email,
this.password,
this.address,
this.addressLat,
this.addressLong,
this.image,
this.mobile,
this.parking,
this.ownerName,
this.token,
this.status,
this.emailVerify,
this.requestStatus,
this.createdAt,
this.updatedAt});

PlaceDetails.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
email = json['email'];
password = json['password'];
address = json['address'];
addressLat = json['address_lat'];
addressLong = json['address_long'];
image = json['image'];
mobile = json['mobile'];
parking = json['parking'];
ownerName = json['owner_name'];
token = json['token'];
status = json['status'];
emailVerify = json['email_verify'];
requestStatus = json['request_status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['email'] = this.email;
data['password'] = this.password;
data['address'] = this.address;
data['address_lat'] = this.addressLat;
data['address_long'] = this.addressLong;
data['image'] = this.image;
data['mobile'] = this.mobile;
data['parking'] = this.parking;
data['owner_name'] = this.ownerName;
data['token'] = this.token;
data['status'] = this.status;
data['email_verify'] = this.emailVerify;
data['request_status'] = this.requestStatus;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}

-------------------------------List widget screen:---------------------------------
class BandRequest_Screens extends StatefulWidget {
@override
_BandRequest_ScreensState createState() => _BandRequest_ScreensState();
}

class _BandRequest_ScreensState extends State<BandRequest_Screens> {
GlobalKey _scaffoldKey = GlobalKey();
var connectionstatus;
var product;
var _isInit = true;
var _isLoading = false;

@override
void initState() {
super.initState();
}

@override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
if (_isInit) {
setState(() {
isLoading = true;
});
Provider.of(context).getBandRequestList().then((
) {
setState(() {
_isLoading = false;
});
});
}
_isInit = false;
super.didChangeDependencies();
}

@override
Widget build(BuildContext context) {
connectionstatus = Provider.of(context);
product = Provider.of(context, listen: false);
// getRequestData();
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
key: _scaffoldKey,
appBar: CustomAppbar(
_scaffoldKey, Constants.requests, 100.0, filterRecord),
endDrawer: MenuDrawer(),
body:
/*(connectionstatus == ConnectivityResult.wifi ||
connectionstatus == ConnectivityResult.mobile)
? */
Consumer(builder: (context, modal, child) {
return !_isLoading
? Container(child: LayoutBuilder(builder:
(BuildContext context, BoxConstraints constraints) {
return Container(
height: constraints.maxHeight,
child: modal.item.length > 0
? ListView.builder(
padding:
EdgeInsets.only(top: 10.0, bottom: 0.0),
itemCount: modal.item.length,
shrinkWrap: true,
// physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, int i) {
return RequestWidgets(data: modal.item[i]);
})
: Center(
child: new Text(
Constants.norecordfound,
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold),
),
),

// ],
// ),
);
}))
: Comman.loadingIndicator(Theme.of(context).primaryColor);
})
// : Comman.nointernetconnection(context)
// FutureBuilder(
// future: Connection.bandRequestList(),
// builder: (context, snapshot) {
// switch (snapshot.connectionState)
// {
// case ConnectionState.none:
// break;
// case ConnectionState.waiting:
// return Comman.loadingIndicator(
// Theme.of(context).primaryColor);
// break;
// case ConnectionState.active:
// break;
// case ConnectionState.done:
// if (snapshot.hasError) {
// return Center(
// child: new Text(Constants.servererror),
// );
// }else if(snapshot.data==null){
// return Center(
// child: new Text(Constants.servererror),
// );
// } else if (snapshot.data.data.length == 0) {
// return Center(
// child: new Text(
// Constants.norecordfound,
// style: TextStyle(
// fontSize: 20.0, fontWeight: FontWeight.bold),
// ),
// );
// } else {
// return ListView.builder(
// padding:
// EdgeInsets.only(top: 10.0, bottom: 60.0),
// itemCount: snapshot.data.data.length,
// shrinkWrap: true,
// physics: NeverScrollableScrollPhysics(),
// itemBuilder: (context, int i) {
// return RequestWidgets(data:snapshot.data.data[i]);
// });
// }
// break;
// }
// }):Comman.nointernetconnection(context)
));
}

Future _onWillPop() async {
return (await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Alert!',
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold)),
content: new Text('Do you want to exit an App?'),
actions: [
new FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('No'),
),
new FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: new Text('Yes'),
),
],
),
)) ??
false;
}
}
------------------------------------List widget child view-----------------------------
class RequestWidgets extends StatefulWidget {
var data;

RequestWidgets({Key key, this.data}) : super(key: key);

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

class _RequestWidgetsState extends State {
var getData;
var product;

@override
void initState() {
// TODO: implement initState
getData = widget.data;
super.initState();
}

@override
Widget build(BuildContext context) {
product = Provider.of(context, listen: false);
return Container(
// alignment: Alignment.topLeft,
margin: EdgeInsets.only(top: 5.0),
child: ListTile(
// contentPadding: EdgeInsets.zero,
key: ObjectKey(getData),
leading: CircleAvatar(
radius: 30,
backgroundColor: Colors.transparent,
child: ClipOval(
child: (getData.placeDetails.image != null &&
getData.placeDetails.image != '')
? Image.network(
getData.placeDetails.image,
width: 90,
height: 90,
fit: BoxFit.cover,
)
: Image.asset(
Res.defaultImage,
width: 90,
height: 90,
fit: BoxFit.cover,
)),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
child: Text(getData.placeDetails.name,
style: TextStyle(
fontSize: 16.0,
fontFamily: 'Metropolis',
color: CustomColors.commentTitleColor))),
],
),
subtitle: Container(
margin: EdgeInsets.only(top: 1.0),
child: Column(children: [
Container(
margin: EdgeInsets.only(top: 1.0),
child: Row(children: [
Expanded(
child: Text(getData.placeDetails.address,
style: TextStyle(
fontSize: 15.0,
height: 1.2,
fontFamily: 'Metropolis',
color: CustomColors.commentSubtitleColor))),
]),
),
Container(
margin: EdgeInsets.only(top: 15.0, bottom: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [],
)),
Divider(
color: CustomColors.commentlineColor,
thickness: 0.8,
)
])),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
GestureDetector(
child: CircleAvatar(
radius: 20,
backgroundColor: Colors.green,
child: Icon(
Icons.check,
color: Colors.white,
),
),
onTap: () {
acceptrejectpopup('1');

// {
// print('accept data $data');
// Comman.hideLoading(context);
// Comman.showSnakBar(data['message'],context);
// });
},
),
SizedBox(
width: 15.0,
),
GestureDetector(
child: CircleAvatar(
backgroundColor: Colors.red,
child: Icon(
Icons.clear,
color: Colors.white,
),
),
onTap: () {
// Comman.showLoading(context);
acceptrejectpopup('0');
/product.acceptdeclinerequest('0',getData.id.toString()).then((data){
print('decline data $data');
Comman.hideLoading(context);
Comman.showSnakBar(data['message'],context);
});
/
},
)
],
),
),
);
}

//accept and reject
void acceptRejectRequest(String requestStatus) async {
try {
var response =
await product.acceptdeclinerequest(requestStatus, getData.id);
if (response['status'] == Constants.status_true) {
Comman.hideLoading(context);
Comman.showSnakBar(response['message'], context);
// setState(() {});
} else {
Comman.hideLoading(context);
}
} catch (exception) {
Comman.hideLoading(context);
Comman.showSnakBar(Constants.servererror, context);
}
}

//request accept/reject popup
Future acceptrejectpopup(String reqStatus) {
return showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Alert!',
style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold)),
content: new Text(reqStatus == '1'
? Constants.reqAcceptmessage
: Constants.reqRejectemessage),
actions: [
new FlatButton(
onPressed: () => Navigator.of(context).pop(),
child: new Text(Constants.notxt),
),
new FlatButton(
onPressed: () {
Navigator.of(context).pop();
Comman.showLoading(context);
acceptRejectRequest(reqStatus);
},
child: new Text(Constants.yestxt),
),
],
),
);
}
}

Souvik Dutta

unread,
Aug 3, 2020, 8:42:16 AM8/3/20
to sumit kumawat, Flutter Development (flutter-dev)
Can to please copy your code to fariyad and provide the link here? It will make the code more readable and probably we can give you answers. 

--
You received this message because you are subscribed to the Google Groups "Flutter Development (flutter-dev)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/43563d4d-6ae5-4ffb-9778-f3c41fbf3e20o%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages