A value of type 'List<Map<String, dynamic>>' can't be assigned to a variable of type 'List<ProjectBoxes>' - flutter

I'm tryng to get a list of boxes to show in a dropdown. But I am can't convert to list map to my object list.
Here's the error message:
A value of type 'List<Map<String, dynamic>>' can't be assigned to a variable of type 'List'.
Try changing the type of the variable, or casting the right-hand type to 'List'.
Here's the code:
import 'package:flutter/material.dart';
import 'package:trfcompactapp/constants.dart';
import '../model/sql_helper.dart';
import '../screens/drawer.dart';
import '../controller/localizationstrf.dart';
class ProjectBoxes {
ProjectBoxes(this.boxId, this.boxName, this.lenght, this.width, this.weight,
this.useLabel, this.labelOrientation, this.createdAt);
int boxId;
String boxName;
int lenght;
int width;
int weight;
int useLabel;
int labelOrientation;
DateTime createdAt;
}
class Project extends StatefulWidget {
const Project({super.key});
#override
State<Project> createState() => _ProjectState();
}
class _ProjectState extends State<Project> {
late ProjectBoxes selectedProjectBox;
#override
void initState() {
super.initState();
_refreshJournals();
}
List<Map<String, dynamic>> _journals = [];
List<Map<String, dynamic>> _journalBoxes = [];
bool _isLoading = true;
// This function is used to fetch all data from the database
void _refreshJournals() async {
final data = await SQLHelper.getProjects();
final dataBoxes = await SQLHelper.getBoxes();
setState(() {
_journals = data;
_isLoading = false;
_journalBoxes = dataBoxes;
boxes = _journalBoxes; // in this line the error happens.
});
}
late List<ProjectBoxes> boxes = <ProjectBoxes>[];
final TextEditingController _projectNameController = TextEditingController();
final TextEditingController _fkProjectBoxController = TextEditingController();
final TextEditingController _fkProjectPalletController =
TextEditingController();
final TextEditingController _fkProjectRobotController =
TextEditingController();
void _showForm(int? id) async {
if (id != null) {
final existingJournal =
_journals.firstWhere((element) => element['projectId'] == id);
final existingJournalBox = _journalBoxes.firstWhere(
(element) => element['boxId'] == existingJournal['FK_project_box']);
_projectNameController.text = existingJournal['projectName'];
_fkProjectBoxController.text =
existingJournalBox['FK_project_box'].toString();
_fkProjectPalletController.text =
existingJournal['FK_project_pallet'].toString();
_fkProjectRobotController.text =
existingJournal['FK_project_robot'].toString();
selectedProjectBox = existingJournalBox[0];
boxes = existingJournalBox[0];
}

It trys to assign List<Map> to a List. You'll have to write a converter to convert the data inside the Map to new ProjectBoxes objects.
Instead of boxes = _journalBoxes; use the following loop:
for (Map<String, dynamic> item in _journalBoxes) {
boxes.add(ProjectBoxes(
field1: item["firstField"] ?? "default value",
field2: item["thirdField"],
field3: item["secondField"] ?? false,
));
}
I don't know the structure of ProjectBoxes so I added some example values:
class ProjectBoxes {
// example fields
String field1;
int? field2;
bool field3;
// constructor
ProjectBoxes({
required this.field1,
this.field2,
required this.field3,
});
}

Related

The argument type 'List<dynamic>' can't be assigned to the parameter type 'Product'

i am trying to add the product to initial state so i can basically show it on the screen.
class _ProductListState extends State
{
var dbHelper = DbHelper();
late List<Product> products;
int productCount = 0;
#override
void initState(){
var productsFuture = dbHelper.getProducts();
productsFuture.then((data){
this.products.add(data);
});
from dbHelper:
Future<List> getProducts() async
{
Database db = await this.db;
var result = await db.query("products");
return List.generate(result.length, (i)
{
return Product.fromObject(result[i]);
});
}
but i get an error. what should i do?
previously, code was like this:
class _ProductListState extends State
{
var dbHelper = DbHelper();
late List<Product> products;
int productCount = 0;
#override
void initState(){
var productsFuture = dbHelper.getProducts();
productsFuture.then((data){
this.products = data;
});
}
try to provide list data type
Future<List<Product>> getProducts() async{

Another exception was thrown: type 'RxList<dynamic>' is not a subtype of type 'List<Vehicle>' in type cast

I want to implement search functionality from database but it shows type cast error
Another exception was thrown: type 'RxList<dynamic>' is not a subtype of type 'List<Vehicle>' in type cast
In my Vehicle_Controller class
final vehicleList = [].obs;
Future<void> getVehicles() async {
List<Map<String, dynamic>> vehicleDetails = await DBHelper.query();
vehicleList.assignAll(vehicleDetails.map((data) => Vehicle.fromJson(data)).toList());
}
I want to implement search in my search class
final _vehicleController = Get.put(VehicleController());
List<Vehicle> _list;
List<Vehicle> _searchList = List();
void initState() {
super.initState();
_IsSearching = false;
_list = _vehicleController.vehicleList as List<Vehicle>; //type cast error
_searchList = _list;
_searchQuery.addListener(() {
if (_searchQuery.text.isEmpty) {
setState(() {
_IsSearching = false;
_searchText = "";
_buildSearchList();
});
} else {
setState(() {
_IsSearching = true;
_searchText = _searchQuery.text;
_buildSearchList();
});
}
});
}
you should use _vehicleController.vehicleList.value as vehicleList is -like the exception says- a RxList not a List
also update this line to be a <Vehicle>[].
final vehicleList = <Vehicle>[].obs;
this will make vehicleList of type RxList<Vehicle>

Why if I modify a T object property all instances project of T object are modified in Dart?

I have two provider classes where as a property there is an instance of a Combo object.
My problem is when I modify value properties of Combo object of provider one, the instance of provider two is modified as well.
This is a problem for me because it makes me impossible to have two different instances even when they are created on different classes.
#immutable class Combo
{
Combo(
{
this.idCombo = 0,
this.idThirdCombo = 0,
this.name = '',
this.urlImage = '',
final List<int>? recipy,
final List<Product>? selectedRecipy,
final List<OptionalRecepy>? optionalRecepy,
final SwitStoreProductType? type,
}) :
this.recipy = recipy ?? [],
this.selectedRecipy = selectedRecipy ?? [],
this.optionalRecepy = optionalRecepy ?? [],
this.type = type ?? SwitStoreProductType.none;
final int idCombo;
final int idThirdCombo;
final String name;
final String urlImage;
final List<int> recipy;
final List<Product> selectedRecipy;
final List<OptionalRecepy> optionalRecepy;
final SwitStoreProductType type;
}
//Provider One
class ProductDetailsBSProvider extends ChangeNotifier
{
Combo? _currentCombo;
void modifyCombo(Product product, int index)
{
if(index != this._currentOptionIndex)
{
if(this._currentCombo!.selectedRecipy.length > 1)
{
int previousIndex = (this._currentCombo!.selectedRecipy.length - 1);
this._currentCombo!.selectedRecipy.removeAt(previousIndex);
this._currentCombo!.selectedRecipy.insert(previousIndex, product);
this._currentOptionIndex = index;
}
else
{
this._currentCombo!.selectedRecipy.add(product);
this._currentOptionIndex = index;
}
}
else
{
if(this._currentCombo!.selectedRecipy.length == 0)
{
this._currentCombo!.selectedRecipy.add(product);
}
else
{
this._currentCombo!.selectedRecipy.removeLast();
this._currentCombo!.selectedRecipy.add(product);
}
}
notifyListeners();
}
}
//Provider Two
class StoreProvider extends ChangeNotifier
{
Combo? _currentCombo;
}
If I print the _currentCombo properties value of Provider Two it will be exactly the same as Provider One

flutter\dart- Loading Json file constantly

I'm trying to load a json file and track the changes. but after the first load it never loads it again.
jsondata = await rootBundle.rootBundle.loadString('assets/data.json');
it seems that it loads it once and keeps that in memory and when it runs through this line again it doesn't load it again so I can't see the json's changes.
here is the json loading and classifying:
class JsonData {
JsonData({
required this.PostUpSale,
required this.WaitingForSpecialDelivery,
required this.SentOrders1,
required this.OutForSpecialDelivery,
required this.StuckOrders,
required this.Shulam,
required this.Name1,
required this.WaitingOrders1,
required this.Display1,
required this.Name2,
required this.WaitingOrders2,
required this.SentOrders2,
required this.Display2,
required this.Name3,
required this.WaitingOrders3,
required this.SentOrders3,
required this.Display3,
required this.Name4,
required this.WaitingOrders4,
required this.SentOrders4,
required this.Display4,
});
late final int PostUpSale;
late final int WaitingForSpecialDelivery;
late final int SentOrders1;
late final int OutForSpecialDelivery;
late final int StuckOrders;
late final int Shulam;
late final String Name1;
late final int WaitingOrders1;
late final bool Display1;
late final String Name2;
late final int WaitingOrders2;
late final int SentOrders2;
late final bool Display2;
late final String Name3;
late final int WaitingOrders3;
late final int SentOrders3;
late final bool Display3;
late final String Name4;
late final int WaitingOrders4;
late final int SentOrders4;
late final bool Display4;
JsonData.fromJson(Map<String, dynamic> json) {
PostUpSale = json['PostUpSale'];
WaitingForSpecialDelivery = json['WaitingForSpecialDelivery'];
SentOrders1 = json['SentOrders1'];
OutForSpecialDelivery = json['OutForSpecialDelivery'];
StuckOrders = json['StuckOrders'];
Shulam = json['Shulam'];
Name1 = json['Name1'];
WaitingOrders1 = json['WaitingOrders1'];
Display1 = json['Display1'];
Name2 = json['Name2'];
WaitingOrders2 = json['WaitingOrders2'];
SentOrders2 = json['SentOrders2'];
Display2 = json['Display2'];
Name3 = json['Name3'];
WaitingOrders3 = json['WaitingOrders3'];
SentOrders3 = json['SentOrders3'];
Display3 = json['Display3'];
Name4 = json['Name4'];
WaitingOrders4 = json['WaitingOrders4'];
SentOrders4 = json['SentOrders4'];
Display4 = json['Display4'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['PostUpSale'] = PostUpSale;
_data['WaitingForSpecialDelivery'] = WaitingForSpecialDelivery;
_data['SentOrders1'] = SentOrders1;
_data['OutForSpecialDelivery'] = OutForSpecialDelivery;
_data['StuckOrders'] = StuckOrders;
_data['Shulam'] = Shulam;
_data['Name1'] = Name1;
_data['WaitingOrders1'] = WaitingOrders1;
_data['Display1'] = Display1;
_data['Name2'] = Name2;
_data['WaitingOrders2'] = WaitingOrders2;
_data['SentOrders2'] = SentOrders2;
_data['Display2'] = Display2;
_data['Name3'] = Name3;
_data['WaitingOrders3'] = WaitingOrders3;
_data['Display3'] = Display3;
_data['Name4'] = Name4;
_data['WaitingOrders4'] = WaitingOrders4;
_data['SentOrders4'] = SentOrders4;
_data['Display4'] = Display4;
return _data;
}
}
void jorgeDeJson() async {
var jsondata = '0';
jsondata = await rootBundle.rootBundle.loadString('assets/data.json');
JsonData userDetails = JsonData.fromJson(jsonDecode(jsondata));
Shulam = userDetails.Shulam;
PostUpSale = userDetails.PostUpSale;
WaitingForSpecialDelivery = userDetails.WaitingForSpecialDelivery;
StuckOrders = userDetails.StuckOrders;
OutForSpecialDelivery = userDetails.OutForSpecialDelivery;
Name1 = userDetails.Name1;
WaitingOrders1 = userDetails.WaitingOrders1;
SentOrders1 = userDetails.SentOrders1;
Name2 = userDetails.Name2;
WaitingOrders2 = userDetails.WaitingOrders2;
SentOrders2 = userDetails.SentOrders2;
Name3 = userDetails.Name3;
WaitingOrders3 = userDetails.WaitingOrders3;
SentOrders3 = userDetails.SentOrders3;
Name4 = userDetails.Name4;
WaitingOrders4 = userDetails.WaitingOrders4;
SentOrders4 = userDetails.SentOrders4;
TotalSent = SentOrders1 + SentOrders2 + SentOrders3 + SentOrders4;
print(TotalSent);
print(Shulam);
}
here is the main loop:
Future<void> main() async {
while (1 == 1) {
print('Before RunUp');
runApp(MyApp());
print('Before Wait');
await Future.delayed(Duration(seconds: 5));
print('After Wait');
jorgeDeJson();
print('After Jorge');
}
}
many thanks!!!!
not sure your process.
//try to await for the json to be loaded
Future<void> main() async {
while (1 == 1) {
print('Before RunUp');
runApp(MyApp());
print('Before Wait');
await Future.delayed(Duration(seconds: 5));
print('After Wait');
await jorgeDeJson(); //<-- here
print('After Jorge');
}
}
Couple of things that are going to ease posible future developments.
you are creating an endless loop, avoid it, instead react to user changes when user changes something.
Future<void> main() async {
runApp(MyApp());
}
MyApp should have the logic to load and refresh when user changes some value previouly loaded from file.
Try to encapsulate concrete functionality, this will allow you to have more granular control
// function to load and return any json data in project bundle
Future<Map<String, dynamic>> parseJsonFromAssets(String assetsPath) async {
return json.decode(await rootBundle.loadString(assetsPath));
}
Future<void> jorgeDeJson() async {
JsonData userDetails = JsonData.fromJson(await parseJsonFromAssets('assets/data.json'));
//..do stuff
}
Another recomendation and if you are the system owner of generated json, try to avoid harcoding, Name1, Name2. Normalize your data.
Meaning:
late final String Name1;
late final int WaitingOrders1;
late final bool Display1;
late final String Name2;
late final int WaitingOrders2;
late final int SentOrders2;
late final bool Display2;
late final String Name3;
late final int WaitingOrders3;
late final int SentOrders3;
late final bool Display3;
late final String Name4;
late final int WaitingOrders4;
late final int SentOrders4;
late final bool Display4;
Reestructuring your your Model and jsonData, will allow you to iterate regardless of waiting orders you might have in the future
List<WaitingOrder> waitingOrders = [
WaitingOrder(
Name: 'name value 1',
Display: 'display value 1'
),
WaitingOrder(
Name: 'name value 2',
Display: 'display value 2'
),
]

Non-nullable instance field '_selectedSize' must be initialized

I have been working with my Store App, but this null safety is getting me pissed now. I have created a class but it gives me this error with later doesn't allow my app to work correctly
this is the the product.dart file:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:loja_virtual_nnananene/models/item_size.dart';
class Product extends ChangeNotifier {
Product.fromDocument(DocumentSnapshot document) {
id = document.documentID;
name = document['name'];
description = document['description'];
images = List<String>.from(document.data['images'] as List<dynamic>);
// ingore_for_file: Warning: Operand of null-aware operation
sizes = (document.data['sizes'] as List<dynamic> ?? [])
.map((s) => ItemSize.fromMap(s as Map<String, dynamic>))
.toList();
}
String id = "";
String name = "";
String description = "";
List<String> images = [];
List<ItemSize> sizes = [];
ItemSize _selectedSize;
ItemSize get selectedSize => _selectedSize;
set selectedSize(ItemSize value) {
_selectedSize = value;
notifyListeners();
}
}
I'm receiving an error at the Product.from...
This is the error:
Non-nullable instance field '_selectedSize' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.
This is my ItemSize class:
class ItemSize {
ItemSize.fromMap(Map<String, dynamic> map) {
name = map['name'] as String;
price = map['price'] as num;
stock = map['stock'] as int;
}
String name = "";
num price = 0;
int stock = 0;
bool get hasStock => stock > 0;
#override
String toString() {
return 'ItemSize{name: $name, price: $price, stock: $stock}';
}
}
Calling in main widget:
class SizeWidget extends StatelessWidget {
const SizeWidget(this.size);
final ItemSize size;
#override
Widget build(BuildContext context) {
final product = context.watch<Product>();
final selected = size == product.selectedSize;
Color color;
if (!size.hasStock)
color = Colors.red.withAlpha(50);
else if (selected)
color = ColorSelect.cprice;
the code tries to get the selected item the first time, and of course it will be null. The alternative I found was...
in ItemSize class, i create a construtor simple with all null -> ItemSize();
class ItemSize {
ItemSize.fromMap(Map<String, dynamic> map) {
name = map['name'] as String;
price = map['price'] as num;
stock = map['stock'] as int;
}
ItemSize();
String? name;
num? price;
int? stock;
bool get hasStock => stock! > 0;
#override
String toString() {
return 'ItemSize{name: $name, price: $price, stock: $stock}';
}
}
in the Product class do the get this way.
ItemSize get selectedSize {
if (_selectedSize != null)
return _selectedSize!;
else
return ItemSize();
}