Flutter短信服务插件mobsms的使用
Flutter短信服务插件mobsms的使用
为开发者提供全球通用的短信验证码工具,开发者可以用其在App植入短信验证码SDK、简单设置即可短信验证,集成快速便捷,且后期易于管理。
开始
-
Flutter集成文档
在项目的
pubspec.yaml
文件中添加mobsms
插件依赖:dependencies: mobsms:
在你的项目Dart代码中添加以下代码以导入
mobsms
包:import 'package:mobsms/mobsms.dart';
-
iOS平台配置
实现 “一、注册应用获取appKey 和 appSecret”
实现 “三、配置appkey和appSecret”
-
Android平台集成
在项目根目录的
build.gradle
文件中添加以下代码:dependencies { classpath 'com.android.tools.build:gradle:3.2.1' classpath 'com.mob.sdk:MobSDK:+' }
在
android/app/build.gradle
文件中添加以下代码:apply plugin: 'com.android.application' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" apply plugin: 'com.mob.sdk'
在
pubspec.yaml
文件中添加mobsms
插件:dependencies: mobsms:
在你的项目Dart代码中添加以下代码以导入
mobsms
包:import 'package:mobsms/mobsms.dart';
在
android/app/build.gradle
文件中添加以下代码:android { // lines skipped dependencies { provided rootProject.findProject(":mobsms") } }
这样就可以在你的
project/android/src
下的类中import cn.smssdk.flutter.MobsmsPlugin
并使用MobsmsPlugin
中的API了。
示例代码
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mobsms/mobsms.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var zoneController = new TextEditingController();
var phoneController = new TextEditingController();
var tempIDController = new TextEditingController();
var codeController = new TextEditingController();
[@override](/user/override)
void initState() {
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('SMSSDK Flutter'),
),
body: new Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
child: new ListView.builder(
itemCount: 1,
itemBuilder: (context, i) => renderRow(i, context),
),
),
),
),
);
}
void showAlert(String text, BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: new Text("提示"),
content: new Text(text),
actions: <Widget>[
new TextButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
)
]));
}
void showPrivacyAlert(String text, BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: new Text("隐私协议"),
content: new Text(text),
actions: <Widget>[
new TextButton(
child: new Text("同意"),
onPressed: () {
// 关闭弹框
Navigator.of(context).pop();
//Mobcommonlib.submitPolicyGrantResult(true, (dynamic ret, Map err) {});
print('smssdk: Smssdk.submitPrivacyGrantResult true');
Smssdk.submitPrivacyGrantResult(true);
},
),
new TextButton(
child: new Text("拒绝"),
onPressed: () {
Navigator.of(context).pop();
//Mobcommonlib.submitPolicyGrantResult(false, (dynamic ret, Map err) {});
print('smssdk: Smssdk.submitPrivacyGrantResult false');
Smssdk.submitPrivacyGrantResult(false);
},
)
]));
}
Widget renderRow(i, BuildContext context) {
return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: 30,
),
Text('请先输入手机号'),
TextField(
controller: zoneController,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(15.0),
labelText: '请输入国家 如:86',
),
),
TextField(
controller: phoneController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(10.0), labelText: '请输入手机号'),
),
TextField(
controller: tempIDController,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(10.0), labelText: '模板编号(没有则不填):'),
),
Container(
height: 30,
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}), foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
})),
child: new Text('请求文本验证码'),
onPressed: () {
Smssdk.getTextCode(phoneController.text, zoneController.text,
tempIDController.text, (dynamic ret, Map? err) {
if (err != null) {
showAlert(err.toString(), context);
} else {
String rst = ret.toString();
if (rst == "") {
rst = '获取验证码成功!';
}
showAlert(rst, context);
}
});
},
),
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}), foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
})),
child: new Text('请求语音验证码'),
onPressed: () {
Smssdk.getVoiceCode(phoneController.text, zoneController.text,
(dynamic ret, Map? err) {
if (err != null) {
showAlert(err.toString(), context);
} else {
showAlert('获取验证码成功!', context);
}
});
},
),
),
TextField(
controller: codeController,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(10.0), labelText: '请输入验证码'),
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}), foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
})),
child: new Text('提交验证码'),
onPressed: () {
Smssdk.commitCode(phoneController.text, zoneController.text,
codeController.text, (dynamic ret, Map? err) {
if (err != null) {
showAlert(err.toString(), context);
} else {
showAlert('提交验证码成功!', context);
}
});
},
),
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}), foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
})),
child: new Text('获取国家列表'),
onPressed: () {
Smssdk.getSupportedCountries((dynamic ret, Map? err) {
if (err != null) {
showAlert(err.toString(), context);
} else {
showAlert(ret.toString(), context);
}
});
},
),
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}), foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
})),
child: new Text('本机号码获取token'),
onPressed: () {
Smssdk.getToken((dynamic ret, Map? err) {
if (err != null) {
showAlert(err.toString(), context);
} else {
showAlert(ret.toString(), context);
}
});
},
),
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}), foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
})),
child: new Text('登陆'),
onPressed: () {
Smssdk.login(phoneController.text, (dynamic ret, Map? err) {
if (err != null) {
showAlert(err.toString(), context);
} else {
showAlert(ret.toString(), context);
}
});
},
),
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}), foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
})),
child: new Text('获取版本号'),
onPressed: () {
Smssdk.getVersion((dynamic ret, Map? err) {
if (err != null) {
showAlert(err.toString(), context);
} else {
showAlert(ret.toString(), context);
}
});
},
),
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}), foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
})),
child: new Text('开启提示框'),
onPressed: () {
Smssdk.enableWarn(true, (dynamic ret, Map? err) {
if (err != null) {
showAlert(err.toString(), context);
} else {
showAlert('开启提示框 成功!', context);
}
});
},
),
),
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: new TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return Colors.blueGrey[700];
}
return Colors.blueGrey;
}),
foregroundColor: MaterialStateProperty.resolveWith((states) {
return Colors.white;
}),
),
child: new Text('打开隐私协议弹框'),
onPressed: () {
showPrivacyAlert('是否同意隐私协议?', context);
},
),
),
],
);
}
}
更多关于Flutter短信服务插件mobsms的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter短信服务插件mobsms的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用mobsms
插件来实现短信服务的示例代码。mobsms
是一个用于集成短信服务的Flutter插件,通常用于发送和接收短信验证码等功能。不过请注意,实际使用时你需要替换成真实的API Key和相关的配置。
1. 添加依赖
首先,你需要在pubspec.yaml
文件中添加mobsms
依赖:
dependencies:
flutter:
sdk: flutter
mobsms: ^最新版本号 # 请替换为实际可用的最新版本号
然后运行flutter pub get
来安装依赖。
2. 配置Android和iOS
Android配置
在android/app/src/main/AndroidManifest.xml
中添加必要的权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<application
...>
<!-- 添加其他配置 -->
</application>
</manifest>
在android/app/build.gradle
中添加Mob的Maven仓库地址(如果mobsms
插件没有自动配置):
allprojects {
repositories {
google()
jcenter()
maven { url 'https://maven.mob.com/nexus/repository/maven-releases/' }
}
}
iOS配置
在ios/Runner/Info.plist
中添加必要的权限描述(如果需要的话):
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>IOSBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<!-- 添加其他必要的配置 -->
3. 初始化并使用MobSMS
在你的Flutter项目中,你可以按照以下方式初始化并使用mobsms
插件:
import 'package:flutter/material.dart';
import 'package:mobsms/mobsms.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('MobSMS Example'),
),
body: Center(
child: MyHomePage(),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _result = '';
@override
void initState() {
super.initState();
// 初始化MobSMS,替换为你的API Key和其他配置
MobSMS.init(
apiKey: '你的API_KEY',
appId: '你的APP_ID',
channel: 'flutter', // 渠道标识,可以是flutter或其他自定义标识
);
}
void _sendSMS() async {
String phoneNumber = '目标手机号'; // 替换为目标手机号
String templateId = '你的模板ID'; // 替换为你的模板ID
String templateParams = '{"code":"123456"}'; // 模板参数,JSON格式
try {
bool success = await MobSMS.sendCode(
phoneNumber: phoneNumber,
templateId: templateId,
templateParams: templateParams,
);
setState(() {
_result = success ? '短信发送成功' : '短信发送失败';
});
} catch (e) {
setState(() {
_result = '发送短信时发生错误: $e';
});
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_result,
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _sendSMS,
child: Text('发送短信'),
),
],
);
}
}
注意事项
- API Key和模板ID:确保你已经在Mob平台上注册并获取了API Key和模板ID。
- 权限处理:在Android上,你可能需要在运行时请求短信权限。Flutter有相应的插件如
permission_handler
可以帮助你处理这些权限请求。 - 错误处理:在实际项目中,你应该添加更详细的错误处理逻辑,以应对各种可能的异常情况。
这段代码提供了一个基本框架,展示了如何在Flutter项目中使用mobsms
插件来发送短信验证码。根据具体需求,你可能需要进一步调整和完善代码。