0

How to access underscore property using reflection in flutter ?. I could not able to find any relevant link regarding this

Ashwin Kmr
  • 280
  • 1
  • 7
  • 20

1 Answers1

1

Even if Dart support reflection through dart:mirrors, Flutter does not. A private property (begining with an underscore) can only be accessed inside the same library.

Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore (_), it’s private to its library. For details, see Libraries and visibility.

You either have to make your field public or to access it from the same library.

Muldec
  • 4,641
  • 1
  • 25
  • 44
  • I have certain private properties in my library inside lib folder.I need to write test scripts using those private properties to cover certain test cases..How can I achieve that..I should not make those private to public.. Without making public I need to achieve this. – Ashwin Kmr Jul 08 '19 at 07:49
  • Private fields are private ! Nothing have to access it from outside the boundary of privacy or it would be a public field. .private field are usually tested by the public methods already present in the code. Calling the public method will use the private field and produce the result that you want. So you are effectively covering the private fields that way, and not by accessing them directly. – Muldec Jul 08 '19 at 07:59
  • 1
    Expanding on what @Muldec already said. If you feel the need to test private members then there might be some problem with your codes structure. Testing the public members of your library should be sufficient. Dart actually does support reflection using dart:mirrors, but flutter uses a special subset of dart that doesn't support the mirrors library. If you actually want to do pure dart unit tests then you might be able to use mirrors to circumvent your design limitations. [so: Get private variable by reflection in dart](https://stackoverflow.com/a/22814830/7036065) – Vincent Engel Jul 08 '19 at 08:54