Dynamic class method invocation in Dart

前端 未结 3 1523
心在旅途
心在旅途 2020-12-10 13:07

Like the question at Dynamic class method invocation in PHP I want to do this in Dart.

var = \"name\";
page.${var} =          


        
相关标签:
3条回答
  • 2020-12-10 13:37

    There are several things you can achieve with Mirrors.

    Here's an example how to set values of classes and how to call methods dynamically:

    import 'dart:mirrors';
    
    class Page {
      var name;
    
      method() {
        print('called!');
      }
    }
    
    void main() {
      var page = new Page();
    
      var im = reflect(page);
    
      // Set values.
      im.setField("name", "some value").then((temp) => print(page.name));
    
      // Call methods.
      im.invoke("method", []);
    }
    

    In case you wonder, im is an InstanceMirror, which basically reflects the page instance.

    There is also another question: Is there a way to dynamically call a method or set an instance variable in a class in Dart?

    0 讨论(0)
  • 2020-12-10 13:39

    You can use Dart Mirror API to do such thing. Mirror API is not fully implemented now but here's how it could work :

    import 'dart:mirrors';
    
    class Page {
      String name;
    }
    
    main() {
      final page = new Page();
      var value = "value";
    
      InstanceMirror im = reflect(page);
      im.setField("name", value).then((_){
        print(page.name); // display "value"
      });
    }
    
    0 讨论(0)
  • 2020-12-10 13:43

    You can use Serializable

    For example:

    import 'package:serializable/serializable.dart';
    
    @serializable
    class Page extends _$PageSerializable {
      String name;
    }
    
    main() {
      final page = new Page();
      var attribute = "name";
      var value = "value";
    
      page["name"] = value;
      page[attribute] = value;
    
      print("page.name: ${page['name']}");
    }
    
    0 讨论(0)
提交回复
热议问题