在Flutter应用中以编程方式获取Dart类中定义的所有“静态常量” [英] Programmatically get all the 'static const' defined in a Dart class in Flutter app

查看:278
本文介绍了在Flutter应用中以编程方式获取Dart类中定义的所有“静态常量”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Dart和Flutter的新手。

I am new to Dart and Flutter.

具体来说,我首先想到了一个简单的问题:以编程方式获取所有图标的名称,扑扑而来。我发现它们在Icons类中被定义为静态常量。因此,如何在运行时以编程方式获取所有这些名称?

Specifically, I started with what I thought would be a simple problem: to programmatically get all the names of the icons that come with flutter. I discovered they are defined as 'static const' in the Icons class. So, how can I programmatically get all of the those names at runtime?

我发现有一个镜像库,但无法正常运行。我尝试了jsonEncode(Icons)来查看可能的操作,但收到错误消息:将对象转换为可编码对象失败:图标。

I discovered that there is a 'mirrors' library but that it won't work in flutter. I tried jsonEncode(Icons) to see what it might do but got the error: "Converting object to an encodable object failed: Icons".

肯定有一个简单的方法

推荐答案

可以在运行时通过编程方式在Dart中获取静态const或类的其他属性的方法? href = https://pub.dev/packages/analyzer rel = nofollow noreferrer> package:analyzer 对Dart代码执行静态分析。此程序包是 dartanalyzer 的功能,因此它的重量很重,但应该能够完成您要执行的操作。

You can use package:analyzer to perform static analysis on Dart code. This package is what powers dartanalyzer, so it's pretty heavy weight but should be able to accomplish what you're looking to do.

例如,我们做一些类似的事情来收集在Dart SDK中进行模糊测试

For example, we do something similar to collect all of the types in the core libraries for fuzz testing in the Dart SDK.

这篇关于在Flutter应用中以编程方式获取Dart类中定义的所有“静态常量”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆