I want to define a constructor that takes fanction as parameter and return a value
Like this:
class app {
app({itemBuilder: itemBuilder});
int itemBuilder(int? index) {
return 1;
}
}
The question is unclear, but here is a snippet of passing the function as a parameter
class app {
final Function app;
app({this.itemBuilder: itemBuilder});
}
final obj = app(itemBuilder: (){
})
I think what you need is the static function to create and return a value.
class AppData890 {
static int itemBuilder(int index) {
return 1;
}
}
use it like this
AppData890.itemBuilder(1);
If you need it as you state the question
Tornike is ri8.
for more info about static head to
https://dart.dev/guides/language/language-tour#class-variables-and-methods
Flutter doesn't allow what you did because The default value of an optional parameter must be constant. Just try with this
class app {
app({itemBuilder});
int itemBuilder(int? index) {
return 1;
}
}
or you can also try and no need to use constructor.
class app {
static int itemBuilder(int? index) {
return index??1;
}
}
// call from outside
app.itemBuilder(5);
Related
Description:
I have already tested methodA() and methodB() so I can be sure that they are covered.
What are the ways to test methodToBeTested() by mocking methodA() and methodB() that are in the same file? The parameters are passed through the methodToBeTested() to the methodA() and methodB() to properly test these methods using injection.
Note: They are cannot be extracted to a different class since it is a related logic of the calculation service and these methods are already atomically is separated.
Code:
class ClassForTesting {
int methodToBeTested(String a, String b) {
// Calculation in this method also is a bit more difficult
return methodA() + methodB();
}
int methodA(String a) {
int value = 1;
// Here is calculation logic that has been tested
return value;
}
int methodB(String b) {
int value = 2;
// Here is calculation logic that has been tested
return value;
}
}
What has been done:
I have tried several approaches from Mockito, but it doesn't allow to do such a trick:
#GenerateMocks - is creating a mock and requires me to stub each method using when(), even methodToBeTested().
By extending Fake using the next construction:
class Mock extends Fake implements PasswordValidatorService {}
But in this way, I'm only inheriting the PasswordValidatorService's behavior instead of instead implementation and each non-overridden method throws UnimplementedError. Thus, I'm not able to override methodToBeTested() and call its super implementation.
I found that Mockito for Java has #Spy construction that would be perfect in this case but unfortunately it is not available for Dart and Flutter.
The only way I currently came is to create my own Mock:
class MockClassForTesting extends ClassForTesting {
#override
int methodA() {
return 2;
}
#override
int methodB() {
return 5;
}
}
But this implementation doesn't allow me to use Mockito's flexibility of when() construction since I must have different methodA() and methodB() returns.
This fact forces me to have additional variables in my MockClassForTesting to achieve when() construction functionality.
The questions:
What would be the best way to achieve my purposes?
Can be the same mocking approach to be used during the Widget testing?
One approach would be to use a hybrid approach where you create your own derived class but where some of its overrides delegate to a Mock implementation. For example:
class ClassForTesting {
int methodToBeTested(String a, String b) {
// Calculation in this method also is a bit more difficult
return methodA(a) + methodB(b);
}
int methodA(String a) {
int value = 1;
// Here is calculation logic that has been tested
return value;
}
int methodB(String b) {
int value = 2;
// Here is calculation logic that has been tested
return value;
}
}
class PartialMockClassForTesting extends ClassForTesting {
final mock = MockClassForTesting();
#override
int methodA(String a) => mock.methodA(a);
#override
int methodB(String b) => mock.methodB(b);
}
#GenerateMocks([ClassForTesting])
void main() {
test('Test partial mock', () {
var partialMock = PartialMockClassForTesting();
when(partialMock.methodA('hello')).thenReturn(42);
when(partialMock.methodA('goodbye')).thenReturn(-42);
when(partialMock.methodB('world')).thenReturn(10);
expect(partialMock.methodToBeTested('hello', 'world'), 52);
expect(partialMock.methodToBeTested('goodbye', 'world'), -32);
});
}
If you want to conditionally mock certain methods, you could have your overrides check boolean flags to conditionally call either the mock or the real implementation. For example:
class PartialMockClassForTesting extends ClassForTesting {
final mock = MockClassForTesting();
final shouldMock = <Function, bool>{};
#override
int methodA(String a) =>
shouldMock[methodA] ?? false ? mock.methodA(a) : super.methodA(a);
#override
int methodB(String b) =>
shouldMock[methodB] ?? false ? mock.methodB(b) : super.methodB(b);
}
#GenerateMocks([ClassForTesting])
void main() {
test('Test partial mock', () {
var partialMock = PartialMockClassForTesting();
partialMock.shouldMock[partialMock.methodA] = true;
partialMock.shouldMock[partialMock.methodB] = true;
...
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.
});
I'm trying to create a function that can dynamically set the properties on an object like so:
void main() {
final obj = Item();
obj.update(5);
print(obj.xVal);
}
class ObjectBase {
void _setData(current, newValue) {
current = newValue;
print(current);
}
}
class Item extends ObjectBase {
int _x;
int get xVal => _x;
update(x) {
_setData(_x, x);
}
}
The print statement in _setData works fine, but it doesn't actually appear to change _x, even if it has been passed through. I expected that changing the reference here would update it everywhere.
So why isn't this working and is there a fix?
You can assume that I do have good reason to be calling _setData inside update rather than just implementing the functionality in update.
Update:
A real life example of what i'm trying to achieve
class ViewModel extends ChangeNotifier {
void _setDataFromDependency(current, newValue) {
if (!deepDynamicEquality(current, newValue)) {
current = newValue;
notifyListeners();
}
}
}
class ListScreenViewModel extends ViewModel {
int _localCount = 0;
List<int> _globalList;
ListScreenViewModel();
List<int> get globalList => _globalList;
int get localCount => _localCount;
incrementLocal() {
_localCount++;
notifyListeners();
}
void update(ListStore listStore) {
_setDataFromDependency(_globalList, listStore.globalList);
// if (!deepDynamicEquality(_globalList, listStore.globalList)) {
// _globalList = listStore.globalList;
// notifyListeners();
// }
}
}
An oversimplified workaround is to return the value from _setData . #julemand101 has already answered limitations.
class ObjectBase {
int _setData(current, newValue) {
current = newValue;
print('current: $current');
return current;
}
}
class Item extends ObjectBase {
int _x;
int get xVal => _x;
update(x) {
_x = _setData(_x, x);
}
}
I have a lot of part of library. But all of the same type (extends Part)
part1.dart
part of Parts;
class Part1 extends Part { /* ... */ }
parts.add((varOfSomeClass){ return new Part1(varOfSomeClass + 1); });
part2.dart
part of Parts;
class Part2 extends Part { /* ... */ }
parts.add((varOfSomeClass){ return new Part2(varOfSomeClass - 1); });
parts.dart
library Parts;
part "Part1.dart";
part "Part2.dart";
List<Function> parts = new List<Function>();
class Parts {
getPart(int index) {
if (parts.contains(index)) {
return parts[index](someVarOfThisClass);
}
}
}
OUTPUT: error: unexpected token 'parts'
How to get all included factories without create instance all the Part classes?
For example need to do:
BMW.dart
part of Auto;
class BMW {
String color;
BMW(this.color);
}
list.add((color){
return new BMW(color);
});
Lada.dart
part of Auto;
class Lada {
List<int> color;
}
list.add((color){
var auto = new Lada();
auto.color = hex2rgb(color);
return auto;
});
Auto.dart
library Auto;
class Auto {
getByIndex(int index) {
if (list.contains(index)) {
return list[index](color);
}
return null;
}
}
Looks like your problem is that you have code outside of a class or function definition. If I'm guessing what you want to do correctly, you want BMW.dart to look something like
part of Auto;
class BMW {
String color;
BMW(this.color);
}
and then in your main() method have code like
main() {
List list = [];
list.add((color) => new BMW(color));
}
This will get the code above running. It's probably not the best way to structure your program though. You may want to do some more reading on Dart factory constructors. https://www.dartlang.org/dart-tips/dart-tips-ep-11.html is a good place to start.
I don't know what you need it for but how about using mirrors:
main.dart
library cars;
import 'dart:mirrors';
part 'bmw.dart';
part 'audi.dart';
abstract class Car {
}
void main() {
List<Car> cars = new List<Car>();
Map libraries = currentMirrorSystem().libraries;
LibraryMirror mirror = libraries[libraries.keys.last];
mirror.declarations.forEach((Symbol s, DeclarationMirror mirror) {
if(mirror is ClassMirror) {
if(!mirror.isAbstract && mirror.isAssignableTo(reflectType(Car))) {
// new Symbol(mirror.reflectedType.toString()))
cars.add(mirror.newInstance(#Car, []).reflectee);
}
}
});
print(cars);
}
bmw.dart
part of cars;
class Bmw extends Car {
Bmw.Car() {
}
}
audi.dart
part of cars;
class Audi extends Car {
Audi.Car() {
}
}
public class Temp
{
List<T> values = new List<T>;
static Temp()
{
System.Console.WriteLine("static constructor");
}
public Temp()
{
System.Console.WriteLine("general constructor");
}
}
Also please explain me when will the List object will be created and with what type it is created.
}
It appears the field gets initialized first, then the static constructor is called, then the constructor.
class Test
{
string variable = new Func<string>(() =>
{
Console.WriteLine("field initializer");
return "VARIABLE";
})();
static string staticvariable = new Func<string>(() =>
{
Console.WriteLine("static field initializer");
return "STATICVARIABLE";
})();
static Test()
{
System.Console.WriteLine("static constructor");
}
public Test()
{
System.Console.WriteLine("general constructor");
}
}
Test t = new Test();
outuput:
static field initializer
static constructor
field initializer
general constructor
[edit]
Oops sorry, it was a non-static field and I didn't notice it.
The static ctor will be called first.
Then values list will be second and the the ctor.
Read about beforefieldinit here.