Dart beginner help needed - dart

var a = [{'answers' : [{'text':'Cloud','score':10},],},];
main()
{
print(a[0]['answers']);
}
I want to print number 10 in 'score'
Anyone help me fix code !!!
Thanks first !!!

Your problem is properly null-safety which complains about using the value from ['answers']. The reason is that the [] operator on Map returns a nullable type because the result can be null in case that the element does not exist in the Map.
I have in the following used ! to promise the compiler that you are sure that the element does exist in the Map so it stops complaining. But it will insert a check on runtime and crash your application in case the returned value is null:
var a = [
{
'answers': [
{'text': 'Cloud', 'score': 10},
],
},
];
void main() {
print(a[0]['answers']![0]['score']); // 10
}

Related

Dart: Constant evaluation error. The method '[]' can't be invoked in a constant expression

I am getting an error on constant evaluation.
please take a look at this code:
class A {
final num a;
const A(this.a);
}
class B {
final A a;
const B(this.a);
}
main() {
const a = A(12);
const b = B(a); // this works fine
// I believe everything inside a const List is considered constant,
// please correct me if that is wrong
const aL = [ A(12), A(13) ]; // [ a, A(13) ] will not work either
const b2 = B(
aL[0], // here the error is happening
);
}
Error:
lib/logic/dartTest.dart:22:14: Error: Constant evaluation error:
const b2 = B(
^
lib/logic/dartTest.dart:23:7: Context: The method '[]' can't be invoked on '<A>[A {a: 12}, A {a: 13}]' in a constant expression. - 'A' is from 'package:t_angband/logic/dartTest.dart' ('lib/logic/dartTest.dart').
aL[0],
^
lib/logic/dartTest.dart:22:9: Context: While analyzing:
const b2 = B(
^
The list contains constant Object, then why the constant evaluation is failing? Shouldn't this be an analyzer issue? Am I missing something?
Thankyou.
Constant expressions can only build data, it cannot deconstruct it. You cannot call any methods on the constant objects except a handful of operations on numbers (and String.length, which also creates a number).
So, aL[0] is simply not a valid compile-time constant expression.
A possible fix may be to make b2 not constant!

Null aware in dart list element

I was working on a project and wanted to check if a list element was null. Example
List<int> i = [1, 2, 3];
print(i[1]); // this prints 2
But what if I want to print out a list element and if it does not exist print out a default number using dart null-aware. Example
List<int> i = [1, 2, 3];
print(i[10] ?? 15);
// Also tried
print(i?.elementAt(10) ?? 15);
I want it to print out 15 since the element at index 10 does not exist. Unfortunately, the above code gives me an error.
How can I check if a list element does not exist and return a default value
There's no elegant way of doing it, as you are trying to. You will have to check the list length first, because in the moment that the program evaluates i.elementAt(10) it inmediately throws the RangeError exception.
Example solution 1:
if (i.length > 9) {
print(i?.elementAt(10));
} else {
print(15);
}
Example solution 2 (a more elegant way):
print(i.length > 9 ? i?.elementAt(10) : 15);
One solution to have this kind of functionality is to wrap your list with a custom class that catches the inner exception and returns null instead.
I wrote this wrapper bellow and called it XList:
class XList<E> {
List<E> list;
XList(this.list);
E operator [](int position) {
try {
return list[position];
} catch(IndexOutOfBoundException) {
return null;
}
}
}
Now your code works like this:
final list = [1, 2, 3];
final a = XList(list);
print(a[10] ?? 15);
// prints 15
You can create an extension on Iterable to easily have a method that returns null if the provided index is out of bounds:
extension SafeAccess<T> on Iterable<T> {
T? safeElementAt(int index) => this.length <= index ? null : this.elementAt(index);
}
you can put this in a general-purpose file like lib/extensions/iterable_extensions.dart in your codebase and then import it whenever you need it.

box callback functions returning the same string in Rascal

I'm trying to draw some boxes in Rascal and trying to give each box its own callback function. On entering the box with the mouse the corresponding string should get displayed in the text element (so hovering box1 should display box1 etc.).
However, at the moment the text does pop up but just displays "box3" for each of the 3 boxes.
Any ideas?
strings = ["box1", "box2", "box3"];
boxes = [ box(
size(100, 100),
onMouseEnter(void() {
output = s;
})
) | s <- strings];
render(hcat([
vcat(boxes),
text(str () {return output;})
]));
Good question, classical problem. The essence of the problem is that Rascal uses "non-capturing closures": this means that functions that are returned from another function share the same context. In your case this is the variable s introduced by s <- strings. This nearly always happens when you create function values in a loop (as you do here). The solution is to wrap another function layer around the returned function.
Here is a simple example:
list[int()] makeClosures()
= [ int() {return i;} | i <- [0,1,2]];
void wrong(){
lst = makeClosures();
println(lst[0]());
println(lst[1]());
println(lst[2]());
}
which will print surprisingly the values 2,2and2`. The solution is, as said, to introduce another function level:
int() makeClosure(int i)
= int() { return i;};
list[int()] makeClosuresOK()
= [ makeClosure(i) | i <- [0,1,2]];
void right(){
lst = makeClosuresOK();
println(lst[0]());
println(lst[1]());
println(lst[2]());
}
now calling right() will print 1, 2, and 3 as expected.
I leave it as an exercise how this is done in your example, but I am prepared to give a solution when you ask for it. Good luck!

JSLint and lodash

i'm using JSLint.NET with lodash. Code like this
var first = _.first(myArray);
will return a Unexpected dangling '_' in '_' error.
How can I exclude this one from being checked?
You want nomen.
/*jslint nomen:true */
var myArray = [],
_ = {},
first;
first = _.first(myArray);
I mean, obviously this assumes you've got a good declaration for _ and myArray somewhere to take the place of the declarations I added, above. A simple underscore is a pretty nasty variable name, but the code above validates on jslint.com. Guessing you're using Underscore.js Lodash, as you mentioned, which means you're probably going to use the global tag instead.
/*jslint nomen:true */
/*globals _ */
var myArray = [],
first;
first = _.first(myArray);

Outputting string depending on color detected in video feed

so what I'm trying to do is output a certain string depending on the color I see in the video feed. For right now, what I've done is threshold the feed so that everything above a certain brightness shows up as Red. Now I want to have something that says if there's any red in the feed, then I output a "1" to a text box on my user interface that's showing the feed. If there is no red, then I output a "0" to the text box. I'm using Emgu CV Managed C++ with VS2010, can anyone help me? Thank you.
This is the code I have so far that isn't working correctly, it's giving me a compiler error.
cvConvertScaleAbs(frameFromCamera->Ptr.ToPointer(),frameDisplay->Ptr.ToPointer(),double(1)/16,0);
cvCvtColor(frameDisplay->Ptr.ToPointer(),frameColorDisplay->Ptr.ToPointer(),CV_GRAY2BGR);
cvThreshold(frameDisplay->Ptr.ToPointer(),maskSaturated->Ptr.ToPointer(),200,255,CV_THRESH_BINARY);
cvNot(maskSaturated->Ptr.ToPointer(),mask1->Ptr.ToPointer());
cv::Scalar red(0,0,255);
cvSet(frameColorDisplay->Ptr.ToPointer(),red,maskSaturated->Ptr.ToPointer());
highColor = gcnew Emgu::CV::Image<Bgr,UInt16>(0, 0, 255);
lowColor = gcnew Emgu::CV::Image<Bgr,UInt16>(0, 0, 200);
if(maskSaturated->InRange(lowColor, highColor) == 255){
tbMorse->Text ="1";
}
else{
tbMorse->Text = "0";
}
imageMain->Image=frameColorDisplay;
and i have highColor and lowColor initialized in my header as such
Emgu::CV::Image<Bgr,UInt16> ^lowColor;
Emgu::CV::Image<Bgr,UInt16> ^highColor;
and the error it's giving me is
BAOTFISInterface.cpp(1010): error C2664: 'Emgu::CV::Image<TColor,TDepth>::Image(int,int,Emgu::CV::Structure::Bgr)' : cannot convert parameter 3 from 'int' to 'Emgu::CV::Structure::Bgr'
with
[
TColor=Emgu::CV::Structure::Bgr,
TDepth=unsigned short
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
BAOTFISInterface.cpp(1011): error C2664: 'Emgu::CV::Image<TColor,TDepth>::Image(int,int,Emgu::CV::Structure::Bgr)' : cannot convert parameter 3 from 'int' to 'Emgu::CV::Structure::Bgr'
with
[
TColor=Emgu::CV::Structure::Bgr,
TDepth=unsigned short
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
BAOTFISInterface.cpp(1013): error C2664: 'Emgu::CV::Image<TColor,TDepth> ^Emgu::CV::Image<TColor,TDepth>::InRange(Emgu::CV::Image<TColor,TDepth> ^,Emgu::CV::Image<TColor,TDepth> ^)' : cannot convert parameter 1 from 'Emgu::CV::Image<TColor,TDepth> ^' to 'Emgu::CV::Image<TColor,TDepth> ^'
with
[
TColor=Emgu::CV::Structure::Gray,
TDepth=unsigned char
]
and
[
TColor=Emgu::CV::Structure::Bgr,
TDepth=unsigned short
]
and
[
TColor=Emgu::CV::Structure::Gray,
TDepth=unsigned char
]
No user-defined-conversion operator available, or
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

Resources