Flutter远程配置插件flutter_rustore_remoteconfig的使用
Flutter远程配置插件flutter_rustore_remoteconfig的使用
准备所需参数
为了运行示例,你需要以下参数:
<code>app_id</code>
- 你的AppId来自Remote Config控制台(https://remote-config.rustore.ru)。- 在控制台创建配置参数。
应用程序设置
- 将文件
flutter_rustore_remoteconfig/example/lib/main.dart
中的app_id
变量替换为你从控制台获取的app_id
。 - 将变量
String? config = ""
替换为控制台中的参数值。
实现示例
为了正确集成remote-config,建议查看应用示例。
项目集成
要将包添加到项目中,请执行以下命令:
flutter pub add flutter_rustore_remoteconfig
这将在pubspec.yaml
文件中添加一行:
dependencies:
flutter_rustore_remoteconfig: ^7.0.0
创建客户端
为了使用配置,我们需要通过方法create
创建一个RemoteConfigClient
:
FlutterRustoreRemoteconfig.create(
appId,
behavior,
interval,
Parameters(),
onBackgroundJobErrors: (value) {
},
onFirstLoadComplete: (value) {
},
onMemoryCacheUpdated: (value) {
},
onInitComplete: (value) {
},
onPersistentStorageUpdated: (value) {
},
onRemoteConfigNetworkRequestFailure: (value) {
});
-
appId
- 你的项目应用ID(Remote config); -
behavior
- SDK更新策略; -
interval
- 更新策略的时间间隔; -
parameters
- SDK静态参数; -
Function? onBackgroundJobErrors, Function? onFirstLoadComplete, Function? onMemoryCacheUpdated, Function? onInitComplete, Function? onPersistentStorageUpdated, Function? onRemoteConfigNetworkRequestFailure
- SDK事件监听器。
获取Remote Config配置
FlutterRustoreRemoteconfig.getRemoteConfig().then(((value) {
}), onError: (err) {
debugPrint("err: $err");
});
方法getRemoteConfig
返回一个RemoteConfig
实例,该实例包含了根据选定的更新策略初始化时获得的所有数据。实例包含所有从服务器传递的键,这些键取决于初始化时指定的参数。
RemoteConfig
类具有获取数据并将其转换为特定类型的以下方法:
containsKey(String key);
getString(String key);
getBool(String key);
getNum(String key);
key
- 控制台Remote Config中创建的参数。
完整示例代码
以下是完整的示例代码:
import 'package:flutter/material.dart';
import 'package:flutter_rustore_remoteconfig/flutter_rustore_remoteconfig.dart';
import 'package:flutter_rustore_remoteconfig/rustore_remote_config.dart';
void main() {
runApp(const MaterialApp(home: StartScreen()));
}
class Parameters extends StaticParameters {
// [@override](/user/override)
// String? get deviceId => "42";
}
class StartScreen extends StatefulWidget {
const StartScreen({super.key});
[@override](/user/override)
State<StartScreen> createState() => _StartScreenState();
}
class _StartScreenState extends State<StartScreen> {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: [
const Text("Choose update behavior"),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => const ConfigScreen(
behavior: PluginUpdateBehavior.actualBehavior),
),
);
},
child: const Text('Actual'),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => const ConfigScreen(
behavior: PluginUpdateBehavior.defaultBehavior),
),
);
},
child: const Text('Default'),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => const ConfigScreen(
behavior: PluginUpdateBehavior.snapshotBehavior,
),
),
);
},
child: const Text('Snapshot'),
),
],
),
),
),
);
}
}
class ConfigScreen extends StatefulWidget {
const ConfigScreen({super.key, required this.behavior});
final PluginUpdateBehavior behavior;
[@override](/user/override)
State<ConfigScreen> createState() => _ConfigScreenState();
}
class _ConfigScreenState extends State<ConfigScreen> {
List<String> stack = [];
String? config = "";
String appId = "ad46fa9e-8e7a-4efb-83c7-47019d327698";
[@override](/user/override)
void initState() {
super.initState();
remoteConfig();
}
void remoteConfig() {
FlutterRustoreRemoteconfig.create(appId, widget.behavior, 15, Parameters(),
onBackgroundJobErrors: (value) {
final item = "onError: $value";
setState(() {
stack.add(item);
});
}, onFirstLoadComplete: (value) {
debugPrint("First load complete");
setState(() {
stack.add("first load");
});
}, onMemoryCacheUpdated: (value) {
debugPrint("memory cache updated");
setState(() {
stack.add("memory cache updated");
});
}, onInitComplete: (value) {
debugPrint("init complete");
setState(() {
stack.add("init complete");
});
}, onPersistentStorageUpdated: (value) {
debugPrint("onPersistentStorageUpdated");
setState(() {
stack.add("onPersistentStorageUpdated");
});
}, onRemoteConfigNetworkRequestFailure: (value) {
final item = "request failure: $value";
setState(() {
stack.add(item);
});
});
}
void getRemoteConfig() {
FlutterRustoreRemoteconfig.init();
FlutterRustoreRemoteconfig.getRemoteConfig().then(((value) {
setState(() {
config = value.getString("SDK_auff_sample");
});
}), onError: (err) {
debugPrint("err: $err");
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Receive config screen'),
),
body: Center(
child: Column(
children: [
Text("Update Behavior: ${widget.behavior}"),
TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: '请输入account',
),
onChanged: (text) {
FlutterRustoreRemoteconfig.setAccount(text);
debugPrint("输入的值: $text");
},
),
TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: '请输入language',
),
onChanged: (text) {
FlutterRustoreRemoteconfig.setLanguage(text);
debugPrint("输入的语言: $text");
},
),
OutlinedButton(
onPressed: () {
FlutterRustoreRemoteconfig.init();
},
child: const Text('init()'),
),
OutlinedButton(
onPressed: () {
getRemoteConfig();
},
child: const Text('getRemoteConfig()'),
),
Text("收到的配置: $config"),
const SizedBox(height: 8),
for (final item in stack) ...[
Text(item),
const SizedBox(height: 4),
],
],
),
),
),
);
}
}
更多关于Flutter远程配置插件flutter_rustore_remoteconfig的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter远程配置插件flutter_rustore_remoteconfig的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_rustore_remoteconfig
是一个用于在 Flutter 应用中集成 RuStore 远程配置功能的插件。RuStore 是俄罗斯的一个应用分发平台,类似于 Google Play Store。通过远程配置,开发者可以动态地更改应用的行为,而无需发布新的应用版本。
以下是如何在 Flutter 项目中使用 flutter_rustore_remoteconfig
插件的步骤:
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 flutter_rustore_remoteconfig
插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_rustore_remoteconfig: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来安装依赖。
2. 初始化远程配置
在你的 Dart 代码中,首先需要初始化远程配置。通常在 main.dart
文件中的 main
函数中进行初始化。
import 'package:flutter/material.dart';
import 'package:flutter_rustore_remoteconfig/flutter_rustore_remoteconfig.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化远程配置
await RustoreRemoteConfig.instance.initialize();
runApp(MyApp());
}
3. 获取配置值
初始化完成后,你可以从远程配置中获取配置值。这些值可以是字符串、布尔值、整数或浮点数。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('RuStore Remote Config Example'),
),
body: Center(
child: FutureBuilder<Map<String, dynamic>>(
future: RustoreRemoteConfig.instance.fetchAndActivate(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
// 获取远程配置的值
String welcomeMessage = RustoreRemoteConfig.instance.getString('welcome_message');
bool isFeatureEnabled = RustoreRemoteConfig.instance.getBool('is_feature_enabled');
int maxItems = RustoreRemoteConfig.instance.getInt('max_items');
double discountRate = RustoreRemoteConfig.instance.getDouble('discount_rate');
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Welcome Message: $welcomeMessage'),
Text('Feature Enabled: $isFeatureEnabled'),
Text('Max Items: $maxItems'),
Text('Discount Rate: $discountRate'),
],
);
}
},
),
),
),
);
}
}
4. 设置默认值
你可以在初始化远程配置时设置默认值,以便在没有网络连接或远程配置未加载时使用这些默认值。
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 设置默认值
Map<String, dynamic> defaults = {
'welcome_message': 'Welcome to the app!',
'is_feature_enabled': false,
'max_items': 10,
'discount_rate': 0.1,
};
// 初始化远程配置并设置默认值
await RustoreRemoteConfig.instance.initialize(defaults: defaults);
runApp(MyApp());
}
5. 触发配置更新
你可以通过调用 fetchAndActivate()
方法来触发配置的更新。这个方法会从远程服务器获取最新的配置,并在获取成功后立即激活。
void updateConfig() async {
bool updated = await RustoreRemoteConfig.instance.fetchAndActivate();
if (updated) {
print('Remote config updated');
} else {
print('Remote config not updated');
}
}
6. 处理配置更新事件
你可以监听配置更新的状态,以便在配置更新时执行某些操作。
RustoreRemoteConfig.instance.addListener(() {
print('Remote config updated');
// 执行某些操作,例如刷新UI
});
7. 其他方法
flutter_rustore_remoteconfig
插件还提供了其他一些方法,例如 getLastFetchStatus()
用于获取上次获取配置的状态,getSource()
用于获取配置值的来源等。
FetchStatus status = RustoreRemoteConfig.instance.getLastFetchStatus();
ValueSource source = RustoreRemoteConfig.instance.getSource('welcome_message');