Declare a class inside a function in dart

Viewed 484

I'm building a library for an API that has hundreds of API functions and result types. For this reason, I made a simple generation script that should create all these types from a definition file.

This is how it was in javascript :

const params = parseTypes();
const api = {}
for (const classParams of params) {
    class VirtualClass{
        className = classParams.name;
        classType = classParams.type;
    }
    api[classParams.name] = VirtualClass;
}

Which worked fine for its purpose but when I tried to implement the same strategy in Dart I couldn't declare a class inside a function. doing the following

void main() {
  class A{
  }
}

gives a lot of red lines and errors

Error: Expected an identifier, but got 'class'.
  class A{
  ^^^^^

Is there a way to implement the same idea in Dart?

1 Answers

Dart does not allow classes to be declared inside functions. I'm not sure if the "same idea" can be implemented some other way, but if you can explain what you are trying to achieve it might be possible to find a different design which does that.

Related