Home > Enterprise >  "#define" equivalent in Dart/Flutter?
"#define" equivalent in Dart/Flutter?

Time:12-25

I wonder if there is a way to #define short_expression long_expression in Dart/Flutter?

For example, instead of typing MediaQuery.of(context).size.width (or Locale.of(context).transate("x")) in every build function, we can #define MQWidth MediaQuery.of(context).size.width(or #define Lt(x) Locale.of(context).transate("x")), then use it in every build function instead?

CodePudding user response:

Macros. Generative programming aka metaprogramming is usually not a thing in interpreted languages. The closest thing to generative programming concept in dart would be static metaprogramming that is actively being chased by. You can currently achieve source code generation in dart via build_runner, which I believe you have seen for example in packages such as json_serializable, and retrofit. But it's still way too far from perfect and requires a lot of work to achieve something even minuscule. And it only fits into certain scenarios and the example you gave is sadly not one of them.

So, the answer is no. You can't do that, at least as of now.

But instead why don't you just separate that into functions if they are really overused all over the place. I know you still have to pass in the context everywhere which is kinda cluttering compared to what you have expected. But it'll still make the code much shorter, if that's your goal.

Hope this answers your question. Cheers!

  • Related