Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement dynamic properties in Dart?

Tags:

dart

I would like to be able to back a dynamic property with a Map using a lookup in noSuchMethod(). However the latest changes makes the incoming property reference name unavailable. I can understand the minification scenario requiring us to use Symbols rather than Strings for names, but this makes implementing serializable dynamic properties difficult. Anyone have good ideas on how to approach this problem?

  • I can't use String names since the String names are not fixed between calls to the minifier. (This would completely break serialization)
like image 753
jz87 Avatar asked May 02 '13 03:05

jz87


People also ask

How do you make a dynamic variable in Dart?

You can use normal global variables in Dart like explained in Global Variables in Dart. final Map<String,int> myGlobals = <String,int>{}; to create a map that stores integer values with string names. Set values with myGlobals['someName'] = 123; and read them with print(myGlobals['someName']); .

What is the difference between dynamic and object in Dart?

There is actually no difference between using Object and dynamic in the example you have given here. There is no practical difference, and you can swap the two and the program will run the same. When I refer to "semantic difference", I mean how the code will be understood by other Dart programmers.

What is dynamic keyword in flutter?

dynamic: can change the TYPE of the variable, & can change the VALUE of the variable later in the code. var: can't change the TYPE of the variable, but can change the VALUE of the variable later in code.

What are properties in Dart?

Properties is a simple library to manage properties files (and something more) in Dart. The project aim is to provide a simple and lightweight implementation of properties file management for Dart adding some useful but not so common features.


1 Answers

You can access the original name with MirrorSystem.getName(symbol)

So a dynamic class could look like :

import 'dart:mirrors';

class A {
  final _properties = new Map<String, Object>();

  noSuchMethod(Invocation invocation) {
    if (invocation.isAccessor) {
      final realName = MirrorSystem.getName(invocation.memberName);
      if (invocation.isSetter) {
        // for setter realname looks like "prop=" so we remove the "="
        final name = realName.substring(0, realName.length - 1);
        _properties[name] = invocation.positionalArguments.first;
        return;
      } else {
        return _properties[realName];
      }
    }
    return super.noSuchMethod(invocation);
  }
}

main() {
  final a = new A();
  a.i = 151;
  print(a.i); // print 151
  a.someMethod(); // throws
}
like image 169
Alexandre Ardhuin Avatar answered Oct 05 '22 12:10

Alexandre Ardhuin