flutter中配置的标准编写方式是什么?

问题描述 投票:0回答:1

我是flutter新手,没有明确的文档来创建配置文件。在flutter中编写配置的标准方法是什么,类似于下面我们在appsettings.json(.net core)中编写的配置?

   "Travel": {
     "EndPoint": "https://api.openai.com/v1/threads",
     "ApiKey": "sk-123",
     "AssistantId": "asst_123"
   },
   "Home": {
     "EndPoint": "https://api.openai.com/v1/threads",
     "ApiKey": "sk-1234",
     "AssistantId": "asst_1234"
   },
   "Edu": {
     "EndPoint": "https://api.openai.com/v1/threads",
     "ApiKey": "sk-123456",
     "AssistantId": "asst_12345"
     }
 }```
flutter dart mobile
1个回答
0
投票

您可以创建一个 Dart 类来表示结构并存储配置数据。具体方法如下:

class AppConfig {
  static const Map<String, Map<String, String>> config = {
    "Travel": {
      "EndPoint": "https://api.openai.com/v1/threads",
      "ApiKey": "sk-123",
      "AssistantId": "asst_123"
    },
    "Home": {
      "EndPoint": "https://api.openai.com/v1/threads",
      "ApiKey": "sk-1234",
      "AssistantId": "asst_1234"
    },
    "Edu": {
      "EndPoint": "https://api.openai.com/v1/threads",
      "ApiKey": "sk-123456",
      "AssistantId": "asst_12345"
    }
  };
}

在这个 Dart 类中:

AppConfig代表配置类。

config 是包含配置数据的静态常量映射。

外层地图的按键代表不同的类别(旅行、家庭、教育)。

每个类别都包含一个带有配置详细信息(EndPoint、ApiKey、AssistantId)的嵌套映射。 然后,您可以在整个应用程序中访问此配置,如下所示:

String travelEndPoint = AppConfig.config["Travel"]["EndPoint"];
String travelApiKey = AppConfig.config["Travel"]["ApiKey"];
String travelAssistantId = AppConfig.config["Travel"]["AssistantId"];

© www.soinside.com 2019 - 2024. All rights reserved.