how to solve the problem in this code class darts after update - dart

I want to ask something, yesterday I was using Dart version 2.10, after I upgraded to version 2.13, I can't run this code can someone help me
class AmtException implements Exception {
String errMsg() => 'Amount should be greater than zero';
}
void withdraw_amt(int amt) {
if (amt <= 0) {
throw new AmtException();
}
}
void main() {
try {
withdraw_amt(-1);
} catch (e) {
print(e.errMsg());
} finally {
print('Ending requested operation.....');
}
}
This output :
Error: The method 'errMsg' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named 'errMsg'.
print(e.errMsg());
^^^^^^

The final code:
class AmtException implements Exception {
String errMsg() => 'Amount should be greater than zero';
}
void withdraw_amt(int amt) {
if (amt <= 0) {
throw new AmtException();
}
}
void main() {
try {
withdraw_amt(-1);
} on AmtException catch (e) {
print(e.errMsg());
} finally {
print('Ending requested operation.....');
}
}
Thanks #jamesdlin

Related

How to get an enum from a String?

Minimal reproducible code:
abstract class FooEnum extends Enum {
// Some abstract methods...
}
enum One implements FooEnum { a, b }
enum Two implements FooEnum { x, y }
FooEnum getFooEnum(String string) {
// Too much boiler plate code, how to do it in a better way?
if (string == 'One.a') return One.a;
else if (...) // other cases.
}
Right now I'm doing it manually (error prone). So, how can I get an enum from a String?
If you only want to use pure dart without flutter or any packages you could do this:
FooEnum? getFooEnum(String string) {
final classValue = string.split('.');
if (classValue.length != 2) {
return null;
}
try {
switch (classValue[0]) {
case 'One':
return One.values.byName(classValue[1]);
case 'Two':
return Two.values.byName(classValue[1]);
}
} on ArgumentError {
return null;
}
return null;
}
With the collection package you could do this:
FooEnum? getFooEnum(String string) {
return (One.values.firstWhereOrNull((e) => e.toString() == string) ??
Two.values.firstWhereOrNull((e) => e.toString() == string)) as FooEnum?;
}
I haven't looked into why the cast is needed, but it was a quick way to fix the problem that occures without it.

Dart The function 'errorMessage' isn't defined

I am new to dart and I am learning dart from youtube. And courses that I am following are of 2018. The programs that they created in their videos are not working. I am facing the below issue in all my programs. Anyone, please guide me that why the programs show errors while the programs are running properly in their videos. Is it happening due to an update in dart? or any other reason? Please help to fix this issue. Thanks!
The function 'errorMessage' isn't defined.
Try importing the library that defines 'errorMessage', correcting the name to the name of an existing function, or defining a function named 'errorMessage'.
class CustomException implements Exception {
String errorMessage() {
return ("Invalid Amount");
}
}
void AmountException(int amount) {
if (amount <= 0) {
throw new CustomException();
}
}
void main() {
try {
AmountException(0);
} catch (e) {
print(errorMessage());
}
}
You are not calling the errorMessage() message on the exception. Another problem is that your catch is set to handle all types of exceptions. Since Exception does not have the errorMessage() method, you cannot call it.
You should therefore specify the type of exception you want to catch which will allow you to call the errorMessage() method on the catched exception:
class CustomException implements Exception {
String errorMessage() {
return ("Invalid Amount");
}
}
void AmountException(int amount) {
if (amount <= 0) {
throw new CustomException();
}
}
void main() {
try {
AmountException(0);
} on CustomException catch (e) {
print(e.errorMessage());
}
}

is there a way to use dependencies injection using typescript

i'm relative new to this, so i want to implement dependency injection using typescript (is the first time I use this pattern), I'm more that using language programming like java or c# for OOP, so there is more easy to apply this pattern,
I found an example on internet and I can use it without problems on eclipse and visual studio, but when i use it on typescript the IDE raise an error like this:
Supplied parameters do not match any signature of call target
and is just at the end of implement it when this error appears
my base class:
class Motor {
Acelerar(): void {
}
GetRevoluciones(): number {
let currentRPM: number = 0;
return currentRPM;
}
}
export {Motor};
my class that uses motor
import { Motor } from "./1";
class Vehiculo {
private m: Motor;
public Vehiculo(motorVehiculo: Motor) {
this.m = motorVehiculo;
}
public GetRevolucionesMotor(): number {
if (this.m != null) {
return this.m.GetRevoluciones();
}
else {
return -1;
}
}
}
export { Vehiculo };
my interface and the type of motor
interface IMotor {
Acelerar(): void;
GetRevoluciones(): number;
}
class MotorGasoline implements IMotor {
private DoAdmission() { }
private DoCompression() { }
private DoExplosion() { }
private DoEscape() { }
Acelerar() {
this.DoAdmission();
this.DoCompression();
this.DoExplosion();
this.DoEscape();
}
GetRevoluciones() {
let currentRPM: number = 0;
return currentRPM;
}
}
class MotorDiesel implements IMotor {
Acelerar() {
this.DoAdmission();
this.DoCompression();
this.DoCombustion();
this.DoEscape();
}
GetRevoluciones() {
let currentRPM: number = 0;
return currentRPM;
}
DoAdmission() { }
DoCompression() { }
DoCombustion() { }
DoEscape() { }
}
and here is where the error appears:
import { Vehiculo } from "./2";
enum TypeMotor {
MOTOR_GASOLINE = 0,
MOTOR_DIESEL = 1
}
class VehiculoFactory {
public static VehiculoCreate(tipo: TypeMotor) {
let v: Vehiculo = null;
switch (tipo) {
case TypeMotor.MOTOR_DIESEL:
v = new Vehiculo(new MotorDiesel()); break;
case TypeMotor.MOTOR_GASOLINE:
v = new Vehiculo(new MotorGasoline()); break;
default: break;
}
return v;
}
}
I don't wanna use any library or module like SIMPLE-DIJS or D4js or any other for the moment, I just wanna know how to implement without them
You have this error because you don't specify a constructor on the Vehiculo type.
To declare a constructor you should use use the constructor keyword and not the name of the class.
class Vehiculo {
private m: Motor;
constructor(motorVehiculo: Motor) {
this.m = motorVehiculo;
}
public GetRevolucionesMotor(): number {
if (this.m != null) {
return this.m.GetRevoluciones();
}
else {
return -1;
}
}
}

How to implement call caching (Memoization)

I want to implement call cache(memoization) in non-intrusive way with the metadata annotations.
Hopefully, it will work like this:
class A{
#Cached
foo(msg) {
return msg;
}
}
void main() {
#Cached
var foo = ()=>"hello";
}
Can it be achieved with only dart:mirrors ?
I wrote a whole blog post on this topic a while ago. It's too long to copy here, so here's the link:
http://dartery.blogspot.com/2012/09/memoizing-functions-in-dart.html
The upshot is that you can write higher-order memoizing functions, but they're limited in generality by Dart's lack of flexible args functions. Also, if you want to use dynamic programming with recursive functions, you need to write your function with memoization in mind - it needs to take itself as an argument, so you can pass in the memoized version.
My current solution allows:
class B {
#CachedCallName(#cachedBaz)
baz() => print("first call to baz");
}
class A extends B with CacheableCalls {
#CachedCallName(#foo)
_foo(msg) {
print("first call with: $msg");
return msg + msg;
}
}
void main() {
A a = new A();
print(a.foo(21));
print(a.foo(21));
a.cachedBaz();
print(a.foo(22));
a.cachedBaz();
}
Output:
first call with: 21
42
42
first call to baz
first call with: 22
44
Flaws:
- can't cache methods with their actual names.
- can extend collection view but can't cache existing operators like operator []
- can't cache functions.
Full source:
#MirrorsUsed(metaTargets: CachedCallName)
import 'dart:mirrors';
class CachedCallName {
final Symbol name;
const CachedCallName(this.name);
}
#proxy
class CacheableCalls {
Map _cache = new Map();
dynamic _chacheInvoke(InstanceMirror thisMirror, Symbol
methodName, Invocation invocation) {
String key = "$methodName${invocation.positionalArguments}"
"${invocation.namedArguments}";
if (_cache.containsKey(key)) {
return _cache[key];
} else {
InstanceMirror resultMirror = thisMirror.invoke(methodName,
invocation.positionalArguments, invocation.namedArguments);
_cache[key] = resultMirror.reflectee;
return resultMirror.reflectee;
}
}
dynamic noSuchMethod(Invocation invocation) {
bool isFound = false;
var result;
Symbol called = invocation.memberName;
InstanceMirror instanceMirror = reflect(this);
ClassMirror classMirror = instanceMirror.type;
classMirror.instanceMembers.forEach((Symbol name, MethodMirror mm) {
mm.metadata.forEach((InstanceMirror im) {
if (im.reflectee is CachedCallName) {
if (im.reflectee.name == called) {
isFound = true;
result = _chacheInvoke(instanceMirror, name, invocation);
}
}
});
});
if (isFound) {
return result;
} else {
throw new NoSuchMethodError(this, called,
invocation.positionalArguments, invocation.namedArguments);
}
}
}
class B {
#CachedCallName(#cachedBaz)
baz() => print("first call to baz");
}
class A extends B with CacheableCalls {
#CachedCallName(#foo)
_foo(msg) {
print("first call with: $msg");
return msg + msg;
}
}
void main() {
A a = new A();
print(a.foo(21));
print(a.foo(21));
a.cachedBaz();
print(a.foo(22));
a.cachedBaz();
}

Override method in dart on fly (like JAVA)

Is there way to overriding method in Dart like JAVA, for example:
public class A {
public void handleLoad() {
}
}
And when overriding:
A a = new A() {
#Override
public void handleLoad() {
// do some code
}
};
No, Dart does not have anonymous classes. You have to create a class that extends A and instantiate it.
No but it much less useful in Dart because you can just reassign function:
typedef void PrintMsg(msg);
class Printer {
PrintMsg foo = (m) => print(m);
}
main() {
Printer p = new Printer()
..foo('Hello') // Hello
..foo = ((String msg) => print(msg.toUpperCase()))
..foo('Hello'); //HELLO
}
However you will need some extra boilerplate to access instance.
Use type Function:
class A {
final Function h
A(this.h);
void handleLoad(String loadResult) { h(loadResult); }
}
Or
class A {
final Function handleLoad;
A(this.handleLoad);
}
A a = new A((String loadResult){
//do smth.
});

Resources