I have two functions which return a value.
protected function createbox():player
{
var face:player = _world.CreateBody(bodydef);
return face;
}
They are identical except that they return a different variable. One returns face, the other returns eyes.
They are executed like this:
_elements.push(new Item(createbox(), new BoxSprite()));
The elements are created. But the problem comes when I try to referece face or eyes. I don't know how to reference them. They don't appear in the debug list of variables. They are null value (outside their functions).
Item is a class file. Which is also a function
public function Item(body:player,sprite:Graphic)
_elements is a vector array.
player is a class
I don't know the syntax to access face and eyes. They always return NULL or property not found no matter where you access them.
Try creating a Global variable. A global variable is available both inside and outside the function definition. So try assigning the variable out of the function and updating its value inside the function.
See example:
var face:String = "This is created out of the function";
function scopeTest(){
face = "This was updated inside the function";
}
scopeTest();
trace(face);
According to your post, faces and eyes are return objects from createbox(), which then are involved in the instantiation process of an Item object, which then is pushed into the _elements vector. Therefore, in order to access faces and eyes, you have to pass these objects to some public references during the constructor of the Item class. After that, you should be able to access them by enumerating wanted Item objects in the vector and using dot syntax on the Item objects.
Related
Why does this code:
class _SequentialTextPageState {
String jsonTextPref = 'seqtext';
int jsonTextSuff = 10;
String jsonText = jsonTextPref + jsonTextSuff.toString();
}
generate these errors?
Error: The instance member 'jsonTextPref' can't be accessed in an initializer.
Error: The instance member 'jsonTextSuff' can't be accessed in an initializer.
It seems to me that concatenation between String and int is correct?
Dart initializes objects in multiple phases. Initializing members directly ("field initializers") occurs early in object initialization, before this becomes valid, so that phase cannot initialize members that depend on other parts of the object.
Dart provides multiple ways to initialize members, so if one member needs to depend on another, you can initialize it in a later phase by using a different mechanism. For example, you could do one of:
Add the late keyword to make the dependent member lazily initialized.
Move initialization of the dependent member into the constructor body.
In the case of a Flutter State subtype, you could initialize the dependent member in its initState method, which in some cases is more appropriate.
Note that in some cases you additionally can consider replacing the member variable with a read-only getter instead. For example, in your case, perhaps you could use:
String get jsonText => jsonTextPref + jsonTextSuff.toString();
That would be appropriate if jsonText should always depend on jsonTextPref and jsonTextSuff, would never need to have an independent value, and if it's acceptable for jsonText to return a new object every time it's accessed.
Dart does not allow field initializers to refer to the object itself. Fields must always be fully initialized before any access is given to the object begin created.
The initializers can only access static and top-level variables, not any instance variables on the object itself.
With null safety, you will be allowed to write late String jsonText = this.something + this.other;. That field will then not be initialized until it's first read or written, which is necessarily after the object itself has been created.
You can only use constant expressions as initializers. x=this.y is not constant.
The error was displayed when I did following:
class MyClass {
String id;
String[] imagePaths;
}
It will mark the String in the line String id; as error, but the error is in the next line, it should be List<String> imagePaths; instead of String[] imagePaths; then the error in the line above also disappears. This can be very confusing if you have a big class and the actual error is many lines underneath the first marked line (talking from experience...)
What is wrong with my code?
widget.woList is this datatype List<HashMap<int, ABC>>()
for (var i in widget.woList) {
print(i.toString());
}
By printing above code, I get
{5838: ABC(pid: 84201,userId: 545)}
But when I want to get only key ( print(i.key.toString());), I get below error:
Class '_HashMap<int, ABC>' has no instance getter 'key'.
Receiver: Instance of '_HashMap<int, ABC>'
Tried calling: key
I think you need to loop through the HashMap as well:
for (HashMap<int, ABC> i in list) {
i.forEach((key, value) {
print(key.toString());
print(value.toString());
});
}
Make sure you typo the "i" variable in the for with HashMap<int, ABC> to get autocompletes from your IDE.
The analyzer should give an error in your case since a Map does not contain any property with the name key. Instead the name is keys which return a Iterable of keys in the map:
https://api.dart.dev/stable/2.8.1/dart-core/Map/keys.html
A map can contain multiple keys but if you know there are only one key in the map you can do something like: i.keys.first.toString(). But if there are multiple keys you need to loop through them.
I will recommend you use auto completion in your IDE when programming in Dart and make use of the analyzer. By using the tools the SDK provides, it is much easier to browse what properties and methods there are in each class together with the documentation. And since Dart can figure out the type of lots of variables automatically, you can use the IDE to also identify the type of each variable without even running the program.
Is it possible to get the type of a variable in Dart at run-time, without having it assigned to an instance of an object and without using mirrors?
I know I can do this without mirrors (which is great!):
Foo foo;
foo = new Foo();
var fooType = foo.runTimeType; // This will give me a type of "Foo"
But I want to know the type of the variable before it is assigned to an object:
Foo foo;
var fooType = foo.runTimeType; // This will not give me a type of "Foo"
I am guessing it is not possible since the typing info is lost in run-time but would like to have it confirmed.
(My actual scenario is that I am doing dependency injection into a Polymer Element using Custom Events. I would like to put as much of this code as possible in an element base-class and have as little code as possible in each derived element class. One thing that I need to do this is to know the type of variables that are to be injected).
I'm new to Dart, so maybe I'm missing something here:
This works:
In my main(), I have this:
var a = _someFunction;
var b = _someFunction;
print("${a == b}"); // true. correct!
Where _someFunction is another top-level function.
This does NOT work: (at least not how I'm expecting it to)
Given this class...
class Dummy {
void start() {
var a = _onEvent;
var b = _onEvent;
print(a == b); // false. ???????
}
void _onEvent() {
}
}
Instantiating it from main() and calling its start() method results in false. Apparently a new instance of some function or closure object is created and returned whenever my code obtains a reference to _onEvent.
Is this intentional behaviour?
I would expect that obtaining multiple references to the same method of the same instance returns the same object each time. Perhaps this is intended for some reason. If so; what reason? Or is this a bug/oversight/limitation of VM perhaps?
Thanks for any insights!
Currently, the behaviour seems to be intentional, but the following defect is open since May 2012: https://code.google.com/p/dart/issues/detail?id=144
If I were to guess, I'd say that setting "var a = _onEvent;" creates a bound method, which is some sort of object that contains both the function as well as this. You are asking for bound methods to be canonicalized. However, that would require the team to create a map of them, which could lead to worries about memory leaks.
I think they made "var a = _someFunction;" work early on because they needed static functions to be constants so that they could be assigned to consts. This was so that they could write things like:
const logger = someStaticLoggingFunction;
This was in the days before statics were lazily evaluated.
In any case, I would say that comparing closures for equality is a edge case for most languages. Take all of the above with a grain of salt. It's just my best guess based on my knowledge of the system. As far as I can tell, the language spec doesn't say anything about this.
Actually, now that I've read (https://code.google.com/p/dart/issues/detail?id=144), the discussion is actually pretty good. What I wrote above roughly matches it.
So here's my factory method which takes a parameter...
container.RegisterInstance<Func<IProductInstance, IQuantityModifier[]>>(
instance => container.Resolve<IQuantityModifier[]>());
Now one of the items returned by the array takes the IProductInsance parameter in its constructor. I can't figure out how to get Unity to pass the parameter in or, if I make the constructor argument a property instead, how to get Unity to set the property. No amount of dependency overrides, injection parameters etc. seem to do anything.
Of course both of these situations would be easy if I was resolving a single instance but with an array Unity doesn't seem to fully process each item.
Any ideas? What I've ended up doing is stuff like this...
container.RegisterInstance<Func<IProductInstance, IQuantityModifier[]>>(
instance =>
{
var items = container.Resolve<IQuantityModifier[]>();
QuantityModifier item = items.OfType<QuantityModifier>().SingleOrDefault();
if (item != null)
{
item.ProductInstance = instance;
}
return items;
};
I suppose ideally the item that requires the parameter would be created by a factory but then Unity would have to pass the correct value into the factory and execute it.
Cheers, Ian.
Sadly, you've hit a bug in the container. A resolve override should do the right thing here. I suspect it's the same underlying cause as this bug: http://unity.codeplex.com/workitem/8777
I'm looking in the source code for the container, the problem is in this method in ArrayResolutionStrategy:
private static object ResolveArray<T>(IBuilderContext context)
{
IUnityContainer container = context.NewBuildUp<IUnityContainer>();
List<T> results = new List<T>(container.ResolveAll<T>());
return results.ToArray();
}
The current set of overrides is part of the current build context, not the container itself, so when it grabs the container and reresolves that context is lost.
Darn, I'll have to figure out how to fix this one.