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

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{

Related

LateInitializationError: Field has not been initialized in flutter unit test

When I run the unit test, I get the error "LateInitializationError: Field 'currentBsTestLocizJson' has not been initialized."
Here is my unit test code
class MockLociz extends Mock implements Lociz{
Map<String, dynamic> currentBsTestLocizJson = {
"verbal_memory_test":"verbal_memory_test",
"tap_words_remember":"tap_words_remember"
};
}
void main() {
late MockLociz mockLociz;
const tTestId = 1;
const tSampleString = "hello world";
setUp(() {
mockLociz = MockLociz();
});
group('get next test screen', () {
test('should return TestTitleAndQATypeParams type object when correct test id is passed',
() async {
// Arrange
// Act
final result = failedTestName(tTestId);
// Assert
expect(result, equals('verbal_memory_test'));
});
});
}
Here is the original Locaize class
class Lociz {
static final Lociz _singleton = new Lociz._internal();
Lociz._internal();
static Lociz get instance => _singleton;
bool locizJsonInitialized = false;
late Map<String, dynamic> currentAthleteLocizJson;
late Map<String, dynamic> currentBsTestLocizJson;
late Map<String, dynamic> currentCommonLocizJson;
}

How to get Single document from firestore and call the fields in UI in flutter/dart

Here is my attempt
In my Controller I have this
class UserController extends GetxController {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
var _proo;
get prooo => _proo;
Future<Member?> readProfile() async {
_proo = FireStoreHelper().fFetch("users", "user1");
}
}
In my FireStoreHelper I have this
class FireStoreHelper {
fFetch(collection, doc) {
final docMember =
FirebaseFirestore.instance.collection(collection).doc(doc);
var query = docMember.get();
return query;
}
This is my Model
class Member {
final String? username;
//...others
Member({
this.username,
//...others
});
static Member fromJson(Map<String, dynamic> json) => Member(
username: json['username'],
//...others
);
}
Then in my UI I have this
Get.lazyPut(() => UserController().readProfile());
return GetBuilder<UserController>(builder: (userController) {
//.......
Text(userController.prooo.username),
}
Actually what am trying get a username of user1 as seen in the Image below
Please help me, I am new to this.
try this one...
fFetch(collection, doc) async {
final docMember = await
FirebaseFirestore.instance.collection(collection).doc(doc).get();
return docMember;
}
static Future<Member?> readProfile() async {
_proo = await FireStoreHelper().fFetch("users", "user1");
Member member = Member.fromJson(_proo);
return member;
}

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

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,
});
}

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>

Getting null values calling method in initState() in flutter

// I called widget from widget
Navigator.of(context).pushNamed('/placebids', arguments: {
'ProductId': productDocumentId,
'ProductName': productName,
});
String productId, productName ;
#override
void initState() {
super.initState();
_fetchBidofAllTheUsersForCompare();
}
Future<void> _fetchBidofAllTheUsersForCompare() async {
final QuerySnapshot _dbr =
await Firestore.instance.collection("Pro-$productName-$productId").getDocuments();
List<DocumentSnapshot> templist;
templist = _dbr.documents;
List<Map<dynamic, dynamic>> list = new List();
list = templist.map((DocumentSnapshot ds) {
return ds.data;
}).toList();
list.forEach((item) => {
item.forEach((key, value) => {
print(value)
})
});
}
Widget build(BuildContext context) {
final routeArguments =
ModalRoute.of(context).settings.arguments as Map<String, String>;
productId = routeArguments['ProductId'];
productName = routeArguments['ProductName'];
return Scaffold();
}
Getting the null values of ProductId and ProductName when i try to call the method in initState();If those values i am receiving in Widget then how to use it in initState method
I faced similar null value problem, the null value problem when I used DocumentSnapshot
final DocumentSnapshot_dbr =
await Firestore.instance.collection("Pro-$productName-$productId").getDocuments();
only documentsnapshot_dbr