Flutter远程配置插件dart_gsheet_remote_config的使用

Flutter远程配置插件 dart_gsheet_remote_config 的使用

dart_gsheet_remote_config 是一个允许你将 Google Sheets 用作 Dart/Flutter 应用程序的远程配置的包。通过这种方式,你可以动态更改应用的行为和设置,而无需更新应用程序本身。

如何工作

该包使用 Query Visualization API 和一些技巧来从 Google Sheet 获取数据。

必读事项

  • 如果你的配置(API 密钥、令牌等)与安全性相关,请不要使用此包,因为它公开且不安全

设置

Google Sheet

  1. 创建一个 Google Sheet 文档,并将其设为公开且只读。如果你没有这样做,将会收到 401 错误。
  2. 在表格中添加数据:
    • 第一列为键
    • 第二列为值
  3. 注意:表中的所有值都标记为字符串。对于整数、双精度浮点数、布尔值,你应该先转换为字符串,可以使用 TO_TEXT 公式进行转换。
  4. 你可以创建多个工作表以更好地管理配置,并选择正确的数据获取。

Dart

dart pub add dart_gsheet_remote_config

Flutter

flutter pub add dart_gsheet_remote_config

如何使用

创建 SheetRemoteConfig 实例

import 'package:dart_gsheet_remote_config/dart_gsheet_remote_config.dart';

final remoteConfig = SheetRemoteConfig();

SheetRemoteConfig 接受一个来自 http 包的 Client 参数,因此你可以传递自定义的 Client 对象。

import 'package:dart_gsheet_remote_config/dart_gsheet_remote_config.dart';
import 'package:http/http.dart' as http;

final client = http.Client();

final remoteConfig = SheetRemoteConfig(client: client);

获取远程配置数据

SheetRemoteConfig 提供了 initialize 方法,你需要传递文档 ID 和工作表名称来初始化远程配置:

  • 文档 ID 可以在 Google Sheet 文档 URL 中找到。例如,URL 为 https://docs.google.com/spreadsheets/d/123456789,则 ID 为 123456789
  • 工作表名称是可选的,默认使用第一个工作表。
await remoteConfig.initialize(id: '123456789'); // 使用第一个工作表

await remoteConfig.initialize(id: '123456789', sheetName: 'Sheet1'); // 使用特定的工作表名称

注意:ID 不应硬编码,建议使用 .env 文件或 dart-define 来传递环境变量。

从远程获取数据

SheetRemoteConfig 以 CSV 格式获取数据,并返回键值对格式的数据。你可以使用以下方法获取不同类型的数据:

final valueKey1 = remoteConfig.getBool('key1');
print(valueKey1); // true

final valueKey2 = remoteConfig.getInt('key2');
print(valueKey2); // 10

final valueKey3 = remoteConfig.getString('key3');
print(valueKey3); // value from key 3

final valueKey4 = remoteConfig.getDouble('key4');
print(valueKey4); // 1.0

如果提供的键未找到或类型不正确,get 函数将返回 null。你可以传递 defaultValue 参数来处理这种情况:

final valueKey5 = remoteConfig.getString('key5', defaultValue: 'this is default value');
print(valueKey5); // this is default value

获取所有数据

SheetRemoteConfig 提供了 getAll 方法来获取所有数据:

final allData = remoteConfig.getAll();
print(allData); // {key1: true, key2: 10, key3: value from key 3, key4: 1.0}

示例 Demo

以下是一个完整的示例代码,展示了如何使用 dart_gsheet_remote_config

import 'package:dart_gsheet_remote_config/dart_gsheet_remote_config.dart';
import 'package:version/version.dart';

Future<void> main() async {
  final remoteConfig = SheetRemoteConfig();

  await remoteConfig.initialize(
      id: "1qEskeRwdtAfnewig-slspPHKafDKV0JMexXdDWgCCeQ");

  final testValue = remoteConfig.getDouble("test");
  print("test: $testValue");

  final themeMode = remoteConfig.getString("themeMode");
  print("themeMode: $themeMode");

  final enableAds = remoteConfig.getBool("enableAds");
  print("enableAds: $enableAds");

  final inAppVersion = Version.parse("1.0.0");

  final currentVersion = remoteConfig.getString("currentVersion");
  print("currentVersion: $currentVersion");

  if (currentVersion != null && inAppVersion < Version.parse(currentVersion)) {
    print("Please update your app");
  } else {
    print("You are using the latest version");
  }
}

更多关于Flutter远程配置插件dart_gsheet_remote_config的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter远程配置插件dart_gsheet_remote_config的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 dart_gsheet_remote_config 插件在 Flutter 应用中实现远程配置的示例代码。这个插件允许你从 Google Sheets 中读取配置数据并在 Flutter 应用中使用这些数据。

首先,确保你的 Flutter 项目中已经添加了 dart_gsheet_remote_config 依赖。在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  dart_gsheet_remote_config: ^最新版本号  # 请替换为实际最新版本号

然后运行 flutter pub get 来获取依赖。

接下来,你需要设置一个 Google Sheets,并将你的 Flutter 应用配置为有权访问这个 Google Sheets。你需要创建一个 Google Cloud 项目,启用 Google Sheets API,并创建一个服务账户,下载其 JSON 密钥文件,并在 Google Sheets 中共享该文件。

以下是一个示例代码,展示了如何在 Flutter 应用中使用 dart_gsheet_remote_config

import 'package:flutter/material.dart';
import 'package:dart_gsheet_remote_config/dart_gsheet_remote_config.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late RemoteConfigService configService;
  Map<String, dynamic>? configData;

  @override
  void initState() {
    super.initState();
    // 替换为你的 Google Sheets URL 和服务账户 JSON 密钥文件的路径
    final sheetUrl = 'https://docs.google.com/spreadsheets/d/你的GoogleSheetsID/edit#gid=0';
    final credentialsPath = 'path/to/your/service-account-file.json';

    configService = RemoteConfigService(sheetUrl: sheetUrl, credentialsPath: credentialsPath);

    // 从 Google Sheets 获取配置数据
    configService.fetchConfig().then((data) {
      setState(() {
        configData = data;
      });
    }).catchError((error) {
      print('Error fetching config: $error');
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Remote Config Example'),
        ),
        body: Center(
          child: configData == null
              ? CircularProgressIndicator()
              : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text('Feature Flag 1: ${configData!['feature_flag_1'] ?? 'Unknown'}'),
                    Text('API Endpoint: ${configData!['api_endpoint'] ?? 'Unknown'}'),
                    // 添加更多配置项展示
                  ],
                ),
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们创建了一个 RemoteConfigService 实例,并传入了 Google Sheets 的 URL 和服务账户 JSON 密钥文件的路径。
  2. initState 方法中,我们调用 fetchConfig 方法从 Google Sheets 获取配置数据,并在获取成功后更新 configData 状态。
  3. build 方法中,我们根据 configData 的状态显示加载指示器或配置项的值。

请确保你已经正确设置了 Google Sheets 和服务账户,并将 URL 和路径替换为你的实际值。

这个示例展示了基本的用法,你可以根据需要扩展和修改以满足你的具体需求。

回到顶部