How can I cast List<TenancyEntity> to List<Tenancy> ?
I use below code but get exception
var a = await _tenancyLocalDataSource.getTenancyList();
var b = a!.cast<Tenancy>();
debugPrint(b.toString());
Below are the both classes
TenancyEntity
import 'package:hive/hive.dart';
import '../../../domain/model/tenancy.dart';
part 'tenancy_entity.g.dart';
#HiveType(typeId: 1)
class TenancyEntity extends HiveObject {
#HiveField(0)
int rentalFees;
TenancyEntity({
required this.rentalFees,
});
Tenancy toTenancy() {
return Tenancy(
rentalFees: rentalFees
);
}
}
Tenancy
import 'package:equatable/equatable.dart';
class Tenancy extends Equatable {
final int rentalFees;
const Tenancy({required this.rentalFees});
#override
List<Object?> get props {
return [rentalFees];
}
#override
bool? get stringify => true;
}
Error
E/flutter ( 6267): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'TenancyEntity' is not a subtype of type 'Tenancy' in type cast
rgjrio iojoijgowrig irjgiorjg dwjoi joifjwoijwio iowjowijoiw wfwf ignore this line
To cast List to List, you can use the map function to convert each TenancyEntity to Tenancy
List<TenancyEntity> a = await _tenancyLocalDataSource.getTenancyList();
List<Tenancy> b = a.map((entity) => Tenancy.fromEntity(entity)).toList();
debugPrint(b.toString());
As you can a method toTenancy in TenancyEntry to to convert the same to Tenancy, you can use map method to solve this.
List<TenancyEntity> a = await _tenancyLocalDataSource.getTenancyList();
List<Tenancy> b = a.map((entity) => entity.toTenancy()).toList();
debugPrint(b.toString());
Related
I have an enum in my model class:
MyRepresentation { list, tabs, single }
I have already added an adapter and registered it.
I have given it a proper type id and fields.
It gives error:
HiveError: Cannot write, unknown type: MyRepresentation. Did you forget to register an adapter?
Did you register the enum too or just the model? Say your model file myrepresentation.dart looks like this:
import 'package:hive/hive.dart';
part 'myrepresentation.g.dart';
#HiveType(typeId: 1)
class MyRepresentation extends HiveObject {
#HiveType(0)
final String id;
#HiveType(1)
final Foo foo;
MyRepresentation({required this.id, required this.foo});
}
#HiveType(typeId: 2)
enum Foo {
#HiveField(0)
foo,
#HiveField(1)
bar,
}
Then you generate you type adapters and initialize both of them in your main:
void main() async {
await Hive.initFlutter();
...
Hive.registerAdapter(MyRepresentationAdapter());
Hive.registerAdapter(FooAdapter());
runApp(MyApp());
}
If you have done this and it is still giving you problems, you could try to put the enum in its own file and write its own part statement.
If this still isn't working I suggest simply storing the enum as int yourself in the TypeAdapter read() and write() methods like this:
#override
MyRepresentation read(BinaryReader reader) {
return MyRepresentation(
reader.read() as String,
Foo.values[reader.read() as int]
);
}
#override
void write(BinaryWriter writer, MyRepresentation obj) {
writer.write(obj.id);
writer.write(obj.foo.index);
}
When I tried to add a new field(intWrkTime)
and I had generated a new adapter, I had this problem although I had initialized it in all my usages.
The error:
Unhandled Exception: type 'Null' is not a subtype of type 'int' in type cast
import 'package:hive/hive.dart';
part 'emp_model.g.dart';
#HiveType(typeId: 0)
class EmployeeModel extends HiveObject
{
#HiveField(0)
late String empName;
#HiveField(2)
late int idWrkTime;
EmployeeModel({
required this.empName,
required this.idWrkTime,
});
}
do like this
#HiveType(typeId: 0)
class TaskEntitiy extends HiveObject {
int id = -1;
#HiveField(0)
String name = '';
#HiveField(1)
bool isCompleted = false;
}
dont put late before fields and give them default amount
Blockquote
I was reading a flutter code as below:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:test_get_app/user_controller.dart';
class AuthMiddleware extends GetMiddleware {
final authService = UserController.findOrInitialize; // Here is error, this line can't find UserController
#override
int? get priority => 1;
bool isAuthenticated = false;
#override
RouteSettings? redirect(String? route) {
isAuthenticated = true;
if (isAuthenticated == false) {
return const RouteSettings(name: '/login');
}
return null;
}
}
When I reached to the following line, I couldn't understand it's syntax and how does it work?
int? get priority => 1;
int? Means it is an int but the int can be null
=> 1 Means () {return 1;}
This is a so-called getter. Getters can be used to provide read access to class properties.
They can also return values directly, like in your case.
They are accessed like properties of the class they are declared in:
final middleWare = AuthMiddleware();
final priority = middleWare.priority;
In your case the getter probably must or can be implemented (see the #override annotation), since all implementations of a middleware must declare their priority, I guess. Since the declared type is int? it may also return null instead of an integer.
Getters can be declared using an expression. Like in your case. Using a block body does also work:
int? get priority {
return 1;
}
Why static keyword is used? Why passing a '-' argument for User?
import 'package:equatable/equatable.dart';
class User extends Equatable {
const User(this.id);
final String id;
#override
List<Object> get props => [id];
*static const empty = User('-');*
}
so I don't have any idea how to take argument from mine Cubit state which is AnswerPicked in this case, there is a code from states file.
part of 'answer_cubit.dart';
abstract class AnswerState extends Equatable {
const AnswerState();
#override
List<Object> get props => [];
}
class AnswerInitial extends AnswerState {}
class AnswerPicked extends AnswerState {
final String answer;
AnswerPicked({
this.answer,
});
String toString() => '{AnswerPicked: $answer}';
}
I want to use it in Cubit function right there:
part 'answer_state.dart';
class AnswerCubit extends Cubit<AnswerState> {
final ExamScoreCubit scoreCubit;
AnswerCubit({
#required this.scoreCubit,
}) : super(AnswerInitial());
List<String> userAnswersList = [];
void pickAnswer(String answer) {
emit(AnswerInitial());
emit(AnswerPicked(answer: answer));
}
void takeAnswer(String questionAnswer, int type) {
if(state is AnswerPicked){
userAnswersList.add(state.answer); // state.answer don't work
scoreCubit.checkAnswer(AnswerPicked().answer, questionAnswer, type); // AnswerPicked().answer don't work
}
emit(AnswerInitial());
}
}
In void takeAnswer() I don't want to pass it throw argument inside the widget tree using context. Any ideas how to do it?
userAnswersList.add((state as AnswerPicked) .answer);