how to delete an object from list in dart - android

i want to delete an object from list of inventory in which i just have description and url of the inventory and i want to delete object of inventory by description so how can i delete the object.
function in service class
Future<dynamic> requestToRemoveInventory(
String accessToken, List<TradeWithPictures> list) async {
try {
var response = await http.patch(Uri.parse(AppUrl.removeInventory),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $accessToken'
},
body: jsonEncode({"inventory": list}));
if (response.statusCode == 200 || response.statusCode == 201) {
var responseJson = jsonDecode(response.body);
return responseJson;
} else {
var responseJson = jsonDecode(response.body);
print(responseJson);
}
} on SocketException {
throw NoInternetException('No Internet Service');
}
}
Function Controller class
deleteInventory(List<TradeWithPictures> list, BuildContext context) async {
String? accessToken = await preferenceService.getAccessToken();
inventoryService.requestToRemoveInventory(accessToken!, list).then((value) {
getMyInvenoryFromService();
}).catchError((error) {
showSnackBar(error.toString(), context);
});
}
please tell me what logic i have to write in view to delete the object. when i am deleting then all list is removed.
this is my view
PopupMenuItem(
onTap: () {
var list = inventoryController
.myInventoryList1
.where((i) =>
i.description !=
inventoryController
.myInventoryList1[
index]
.description)
.toList();
inventoryController
.deleteInventory(
list, context);
},
value: 1,
child: Padding(
padding:
const EdgeInsets.all(
8.0),
child: Text(
"Delete",
style: TextStyle(
color: AppColors
.pinkAppBar,
fontWeight:
FontWeight.w700),
),
),
),

Here is a simple example of how you can filter out your results from a list,
filteredResulst = AllRecords.where((i) => i.aParticularProperty === thingToCompare ).toList();

Related

Parsing Json in flutter - Does not show data

I am developing an android application with flutter, what I am doing is displaying a json in an application page. When I run the application it doesn't give me an error but it doesn't show me the data, the json I want to read is the following:
[
{
"deviceid": 27,
"f2cuid": "Estacion1_A",
"devicedata": {
"isRunning": 0,
"color": "w3-red",
"colorNoW3": "red",
"device_name": "Estacion1_A"
}
},
{
"deviceid": 20,
"f2cuid": "B19",
"devicedata": {
"isRunning": 1,
"color": "w3-green",
"colorNoW3": "green",
"device_name": "B19"
}
}
]
It's in my model class:
class Stations {
Int? isRunning;
String? color;
String? colorNoW3;
String? devicename;
Stations(
{this.isRunning,
this.color,
this.colorNoW3,
this.devicename,
});
factory Stations.fromJson(Map<String, dynamic> json) {
return Stations(
isRunning: json['isRunning'],
color: json['color'],
colorNoW3: json['colorNoW3'],
devicename: json['device_name'],
);
}
}
This is my service:
Future<List<Stations>> getStations() async {
Uri url = Uri.parse('URL');
final response = await http.get(url);
var data = jsonDecode(response.body);
print('data: $data');
List<Stations> stations = data.map((e) => Stations.fromJson(e)).toList();
return stations;
}
and this is the way I display it:
return Scaffold(
appBar: AppBar(
title: const Text('Sistema Escolar Administrativo'),
),
drawer: DrawerWidgetMenu(),
body: Container(
child: FutureBuilder(
future: stationSvc.getStations(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Container(
child: Center(
child: Text('No hay datos que mostrar'),
),
);
}
return snapshot.data.length > 0
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: InkWell(
onTap: () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => HomePage(),
),
);
},
child: ListTile(
leading: Text(snapshot.data[index].devicename!),
title: Text(snapshot.data[index].color!),
subtitle: Text(snapshot.data[index].colorNoW3!),
),
));
})
: Center(
child: Text('No hay datos, registra un grupo primero'));
}),
),
);
You forgot to specify nested map:
factory Stations.fromJson(Map<String, dynamic> json) {
return Stations(
isRunning: json['devicedata']?['isRunning'],
color: json['devicedata']?['color'],
colorNoW3: json['devicedata']?['colorNoW3'],
devicename: json['devicedata']?['device_name'],
);
}
I am sharing a complete class named SampleModel below which can help to parse JSON in flutter:
class SampleModel {
String? _myName;
bool? _isActive;
SampleModel({String? myName, bool? isActive}) {
if (myName != null) {
_myName = myName;
}
if (isActive != null) {
_isActive = isActive;
}
}
String? get myName => _myName;
set myName(String? myName) => _myName = myName;
bool? get isActive => _isActive;
set isActive(bool? isActive) => _isActive = isActive;
SampleModel.fromJson(Map<String, dynamic> json) {
_myName = json['myName'];
_isActive = json['isActive'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['myName'] = _myName;
data['isActive'] = _isActive;
return data;
}
}
Sample JSON for the same class:
{
"myName" : "Your Name",
"isActive" : true
}
Check if this can help in your case.
your json type is an array, not a map.
look at [ ] syntax on json file.
to deal with an Array, you should make it to a list first:
List<Map<String,dynamic>> mylistofMapformJson = json.decode(receivedJson);
//you should get your list stations like this:
List<Stations> listStationsFromJson = List.generate(
mylistofMapformJson.length,
(index) => Stations.fromJson(mylistofMapformJson));

Json Empty after parse even though status 200

I am trying to parse a JSON after doing a HTTP GET request for my flutter app, however when it is parsed, the body shows as empty, this is the parsing code
urlHausParseBox() {
Future<_GoneSmishinState> fetchUrlResponse() async {
String url = myController.text;
final response = await http.post(
Uri.parse("https://urlhaus-api.abuse.ch/v1/url/"),
headers: <String, String>{
'Accept': 'application/json',
},
body: (<String, String>{
'url': url,
'query_status': query_status,
'url_status' : url_status,
//'status' : status,
//'urlStatus' : urlStatus,
}));
After this I have a check for the 200 status, and when recieved will return this to use after the fact, I printed the fields 'query_status' and 'url_status' but they came up empty so I printed what I was returning here
if (response.statusCode == 200) {
print (_GoneSmishinState.fromJson(jsonDecode(response.body)));
return _GoneSmishinState.fromJson(jsonDecode(response.body));
but all that is printed out is _GoneSmishinState#23f48(lifecycle state: created, no widget, not mounted)
which is not what is supposed to be returned by the HTTP GET request
The rest of my code is below
import 'dart:convert';
import 'package:validators/validators.dart';
import 'package:flutter/material.dart';
import 'package:sms/sms.dart';
import 'dart:io';
import 'dart:developer' as developer;
import 'package:http/http.dart' as http;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
String url = "https://urlhaus-api.abuse.ch/v1/urls/recent/"; //address for URL file
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key:key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: "Gone Smishin'",
home: GoneSmishin(),
);
}
}
class GoneSmishin extends StatefulWidget {
const GoneSmishin({Key? key}) : super(key: key);
State<GoneSmishin> createState() {
return _GoneSmishinState(url_status: '', query_status: '');
}
}
class _GoneSmishinState extends State<GoneSmishin> {
String message = "";
String word = "";
bool isOn = false;
final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
super.dispose();
}
_GoneSmishinState({
required this.query_status,
required this.url_status,
});
final String query_status;
final String url_status;
factory _GoneSmishinState.fromJson(Map<String, dynamic> json) {
return _GoneSmishinState(
query_status: json["query_status"],
url_status: json["url_status"],
);
}
urlHausParseBox() {
Future<_GoneSmishinState> fetchUrlResponse() async {
String url = myController.text;
final response = await http.post(
Uri.parse("https://urlhaus-api.abuse.ch/v1/url/"),
headers: <String, String>{
'Accept': 'application/json',
},
body: (<String, String>{
'url': url,
'query_status': query_status,
'url_status' : url_status,
}));
if (response.statusCode == 200) {
print (_GoneSmishinState.fromJson(jsonDecode(response.body)));
return _GoneSmishinState.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load website');
}
}
fetchUrlResponse();
if (query_status == "ok" && url_status == "online") {
const Text ('Found in URLHause Database - Probably Smishing');
print("found");
} else if (query_status == "ok" && url_status == "offline") {
const Text ('Found in URLHaus, not online');
print("found offline");
} else {
const Text ('Found Nothing');
print("not found");
print (query_status);
print (url_status);
}
_pushInput() {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) {
return Scaffold(
appBar: AppBar(
title: const Text ('Submit a Link')
),
body: (
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField (
controller: myController,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter your Link Text',
contentPadding: EdgeInsets.symmetric(
vertical: 40, horizontal: 20),
),
),
ElevatedButton(
onPressed: () {
urlHausParseBox();
},
child: const Text('Submit')
)
]
)
));
}
)
);
}
#override
var buttonText = 'OFF';
String textHolder = "App is Off";
changeTextON() {
setState(() {
textHolder = "App is ON";
});
isOn == true;
}
changeTextOFF() {
setState(() {
textHolder = "App is OFF";
});
isOn == false;
}
Widget build(BuildContext context) {
final ButtonStyle outlineButtonStyle = OutlinedButton.styleFrom(
primary: Colors.black87,
minimumSize: Size(200, 130),
padding: EdgeInsets.symmetric(horizontal: 200),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(300)),
),
).copyWith(
side: MaterialStateProperty.resolveWith<BorderSide>(
(Set<MaterialState> states) {
return BorderSide(
color: Theme.of(context).colorScheme.primary,
width: 1,
);
},
),
);
return Scaffold(
appBar: AppBar(
title: const Text("Gone Smishin'"),
actions: [
IconButton(
icon: const Icon(Icons.add_link),
onPressed: _pushInput,
tooltip: 'Submit a Link'
)
],
backgroundColor: Colors.red,
),
body: Column (
children: [
Container(
padding: EdgeInsets.fromLTRB(50, 50, 50, 50),
child: Text('$textHolder',
style: TextStyle(fontSize: 50)
),
),
Container(
//child: Text(result)
),
TextButton(
style: outlineButtonStyle,
onPressed: () {
changeTextON();
},
child: Text('ON')
),
TextButton(
style: outlineButtonStyle,
onPressed: () {
changeTextOFF();
},
child: Text("OFF"),
)
]
),
);
}
}
Change this:
_GoneSmishinState({
required this.query_status,
required this.url_status,
});
final String query_status;
final String url_status;
factory _GoneSmishinState.fromJson(Map<String, dynamic> json) {
return _GoneSmishinState(
query_status: json["query_status"],
url_status: json["url_status"],
);
}
to this:
_GoneSmishinState();
var queryStatus = '';
var urlStatus = '';
and this:
if (response.statusCode == 200) {
print (_GoneSmishinState.fromJson(jsonDecode(response.body)));
return _GoneSmishinState.fromJson(jsonDecode(response.body));
}
to:
if (response.statusCode == 200) {
setState(() {
final decoded = json.decode(response.body);
queryStatus = decoded['query_status'];
urlStatus = decoded['url_status'];
}
);
}
And, finally, patch up any unused/misnamed variables. As an aside, it's difficult to read functions declared inside other functions. Is fetchUrlResponse inside urlHausParseBox? Move it outside.

Getting null values in View Flutter

I want to get data of inventory but not getting. I am doing API integration without model because there are some issues in Model just to get data and want to display in to my view.
this is my service class of get data through API.
Future<dynamic> getInventory() async {
var data;
String? userId = await preferenceService.getuserId();
String? accessToken = await preferenceService.getAccessToken();
var response = await http.get(Uri.parse('${AppUrl.getInventory}/$userId'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Barear $accessToken'
});
print("The data of the specific inventory ===========>>>>>>>> " +
response.body.toString());
if (response.statusCode == 200) {
data = jsonDecode(response.body);
print('This is futr dsta --->>> $data');
} else {
data=[];
}
return data;
}
This is my controller class where i am using above service function
Future getMyInvenoryFromService() async {
try {
isLoadingInventory(true);
await inventoryService.getInventory().then((val) {
if (val != []) {
inventoryData = val;
} else {
inventoryData = [];
}
});
} finally {
isLoadingInventory(false);
}
}
But when i am accessing the data with inventoryData (in controller) i am getting null, but in controller i am getting values when debugging. but i am not understanding why i am receiving null values in view.
This is my view,
class _UserInventoryScreenState extends State<UserInventoryScreen> {
InventoryController inventoryController = Get.put(InventoryController());
InventoryService inventoryService = InventoryService();
GiftController giftController = Get.put(GiftController());
GiftStorageService giftStorageService = GiftStorageService();
#override
void initState() {
super.initState();
/*Future delay() async {
await new Future.delayed(new Duration(milliseconds: 3000), () {
inventoryController.getMyInvenoryFromService();
});
}*/
Timer.run(() {
inventoryController.getMyInvenoryFromService();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.pinkAppBar,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
leading: InkWell(
onTap: () {
Get.back();
},
child: Icon(Icons.arrow_back)),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Inventory'),
InkWell(
onTap: () {
Get.to(AddInventoryScreen());
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration:
BoxDecoration(border: Border.all(color: Colors.white)),
child: Text(
"Add Inventory",
style: TextStyle(fontSize: 16),
),
),
)
],
),
),
body: Obx(() {
return inventoryController.isLoadingInventory.value == true
? Center(child: CircularProgressIndicator())
: ElevatedButton(
onPressed: () async {
await inventoryController.getMyInvenoryFromService();
},
child: Text("${inventoryController.inventoryData.length}"),
);
If your response.statusCode isn't 200 it might be because you are setting wrong your headers:
'Authorization': 'Barear $accessToken'
Change it to:
'Authorization': 'Bearer $accessToken'

how to delete an object from list in flutter

i want to delete an object from list of inventory in which i just have description and url of the inventory and i want to delete object of inventory by description so how can i delete the object.
function in service class
this is my service class
Future<dynamic> requestToRemoveInventory(
String accessToken, List<Inventory> list) async {
try {
var response = await http.patch(Uri.parse(AppUrl.removeInventory),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $accessToken'
},
body: jsonEncode({"inventory": list}));
if (response.statusCode == 200 || response.statusCode == 201) {
var responseJson = jsonDecode(response.body);
return responseJson;
} else {
var responseJson = jsonDecode(response.body);
print(responseJson);
}
} on SocketException {
throw NoInternetException('No Internet Service');
}
}
This is my Controller class
deleteInventory(List<Inventory> list, BuildContext context) async {
String? accessToken = await preferenceService.getAccessToken();
inventoryService.requestToRemoveInventory(accessToken!, list).then((value) {
getMyInvenoryFromService();
}).catchError((error) {
showSnackBar(error.toString(), context);
});
}
please tell me what logic i have to write in view to delete the object. when i am deleting then all list is deleting at a time
This is my view
PopupMenuButton(
itemBuilder: (context) => [
PopupMenuItem(
onTap: () {
var list = inventoryController
.myInventoryList1
.where((i) =>
i.description !=
inventoryController
.myInventoryList1[
index]
.description)
.toList();
inventoryController
.deleteInventory(
list, context);
},
value: 1,
child: Padding(
padding:
const EdgeInsets.all(
8.0),
child: Text(
"Delete",
style: TextStyle(
color: AppColors
.pinkAppBar,
fontWeight:
FontWeight.w700),
),
),
),
You can use removeWhere
PopupMenuItem(
onTap: () {
var list = inventoryController
.myInventoryList1;
//if you want to remove a single object from list
list.removeWhere((i) =>
i.description ==
list[index].description);
//if you want the only element in the list.
var updateList = list.firstWhere((i) => i.description ==
list[index].description)
inventoryController
.deleteInventory(
list, context);
}
Removing Objects and indexes into the list
List.remove(Object value)
Example of Removing Objects into the list
List l = [1, 2, 3,4,5,6,7,8,9];
bool res = l.remove(1);
Result
[2, 3, 4, 5, 6, 7, 8, 9]
List.removeAt(int index)
Example of Removing Index into the list
List l = [1, 2, 3,4,5,6,7,8,9];
bool res = l.removeAt(1);
result
[1, 3, 4, 5, 6, 7, 8, 9]
Try this way
Here, List contains Inventory class all data. Find or remove data by List object.
List<Inventory> list;
//For removing specific item from a list with the attribute value
list.removeWhere((item) => item.id == '001')
//Remove item by specifying the position of the item in the list
list.removeAt(2)
//Remove last item from the list
list.removeLast()
//Remove a range of items from the list
list.removeRange(2,5)
If you raise any issue raise your query to us.

type 'Future<List<Data>>' is not a subtype of type 'List<Data>' in type cast

I am getting the data from server and trying to set it in a grid view but I am getting error:
type 'Future<List<Data>>' is not a subtype of type 'List<Data>' in type cast
Here is my Data Class:
class Data with ChangeNotifier {
Data({
this.name,
this.image,
});
final String image;
final String name;
factory Data.fromJson(Map<String, dynamic> json) {
print(json['title'].toString());
return Data(
name: json['title'].toString(),
image: json['image'].toString(),
);
}
}
And this is my Data_screen where I am calling this:
var datas= Provider.of<Datas>(context).fetchData() as List<Data>;
var datalength = datas.length;
Widget:
Expanded(
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
padding: EdgeInsets.only(left: 28, right: 28, bottom: 58),
itemCount: datas.length,
itemBuilder: (context, index) => DataCard(
datas[index],
index: index,
onPress: () {
},
),
),
),
And in Datas.dart:
Future<List<Data>> fetchData() async {
var response = await http.get(url);
var responseJson = json.decode(response.body);
print(responseJson);
return (responseJson['datas'])
.map<Data>((p) => Data.fromJson(p))
.toList();
}
The message is so clear. You cannot cast from List<Data> to Future<List<Data>>. Try to use:
List<Data> fetchData() async {
var response = await http.get(url);
var responseJson = json.decode(response.body);
print(responseJson);
return (responseJson['datas'])
.map<Data>((p) => Data.fromJson(p))
.toList();
}
OR return a new Future with the List<Data>
Future<List<Data>> fetchData() async {
var response = await http.get(url);
var responseJson = json.decode(response.body);
print(responseJson);
var response = (responseJson['datas'])
.map<Data>((p) => Data.fromJson(p))
.toList();
return Future.value(response)
}
It just an idea(without testing)

Categories

Resources