Flutter亚马逊服务集成插件flutter_amz_sdk的使用

Flutter亚马逊服务集成插件flutter_amz_sdk的使用

第一步: 从官网后台申请 token,例如:“820771247e8bf476”

在开始使用 flutter_amz_sdk 插件之前,您需要从亚马逊服务的官方后台申请一个开发者 token。该 token 是用于标识您的开发者的身份。

初始化插件:

final _flutterAmzSdkPlugin = FlutterAmzSdk.instance;

API

方法列表

  • 设置开发者申请到的 token
    setDeveloperToken(String token, {bool debug = false})
    
  • 搜索玩具
    searchToys()
    
  • 停止搜索玩具
    stopSearching()
    
  • 连接玩具
    connectToy(String toyId)
    
  • 是否已经连接玩具
    isConnected(String toyId)
    
  • 发送控制指令
    sendCommand(String toyId, int command, [int process = -1, List<int> levels])
    
  • 读取玩具信号
    rssiData(String toyId)
    
  • 获取玩具信息
    getDeviceInfo(String toyId)
    
  • 获取指令合集
    command
    

Command

指令列表

  • 发送通用震动指令
    command.sendCommonCommand()
    
  • 发送伸缩指令
    command.sendAdjustableCommand()
    
  • 发送充气指令
    command.sendAerateCommand()
    
  • 发送清除指令, 停止设备动作
    command.sendClearActionCommand()
    
  • 发送自定义指令
    command.sendCustomizeCommand()
    
  • 发送放气指令
    command.sendDeflationCommand()
    
  • 发送浮动指令
    command.sendFloatCommand()
    
  • 发送获取设备信息指令
    command.sendGetDeviceInfoCommand()
    
  • 发送获取版本信息指令
    command.sendGetVersionInfoCommand()
    
  • 发送获取版本升级信息指令
    command.sendGetVersionUpgradeInfoCommand()
    
  • 发送加热指令
    command.sendHeatingCommand()
    
  • 发送灯光指令
    command.sendLightingCommand()
    
  • 发送循环指令
    command.sendLoopCommand()
    
  • 发送系统内置模式指令
    command.sendSystemCommand()
    
  • 发送旋转指令
    command.sendWhirlingCommand()
    
  • 发送手动模式指令
    command.sendManualModeCommand()
    
  • 发送视频采点模式指令
    command.sendSavePornModelCommand()
    
  • 发送伸缩距离指令
    command.sendStrokeModeCommand()
    

回调监听

监听事件

  • 连接状态
    _flutterAmzSdkPlugin.connectedStream
    
  • 扫描状态
    _flutterAmzSdkPlugin.scanStream
    
  • 读信号
    _flutterAmzSdkPlugin.rssiStream
    
  • 获取设备信息
    _flutterAmzSdkPlugin.infoStream
    
  • 获取设备角速度
    _flutterAmzSdkPlugin.gsensorStream
    

示例

subscription = _flutterPlugin.rssiStream.listen((event) {
  if(mounted) {
    setState(() {
      rssi = event.rssi;
    });
  }
});
subscription1 = _flutterPlugin.connectedStream.listen((event) {
  print('connectedStream : ${event.toString()}');
  if(event.state == AMZToyState.stateFailed) {
    showToast('disconnect');
    if(mounted) {
      Navigator.of(context).pop();
    }
  }
});

subscription2 = _flutterPlugin.infoStream.listen((event) {
  print('infoStream : ${event.toString()}');
});

完整示例代码

以下是一个完整的示例代码,展示如何使用 flutter_amz_sdk 插件来实现基本功能。

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_amz_sdk/flutter_amz_sdk.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late final _flutterAmzSdkPlugin = FlutterAmzSdk.instance;
  final token = "4146e39d-f803-4bdf-b79e-cf21f65d2592";
  List<AMZToy> list = [];
  int itemIndex = -1;
  AMZToy? mAMZToy;
  late StreamSubscription subscription;
  late StreamSubscription subscription1;
  late StreamSubscription subscription2;
  late StreamSubscription subscription3;
  late StreamSubscription subscription4;

  [@override](/user/override)
  void initState() {
    super.initState();
    subscription = _flutterAmzSdkPlugin.connectedStream.listen((event) {
      print("connectedStream2:$event");
      if (event.state == AMZToyState.stateConnected) {
        showToast('connected');
      }
      if (event.state == AMZToyState.stateFailed) {
        showToast('disconnect');
      }
    });
    subscription2 = _flutterAmzSdkPlugin.toyConfigsStream.listen((event) {
      print('toyConfigsStream: ${event.length}');
    });
    subscription1 = _flutterAmzSdkPlugin.bleStateStream.listen((event) {
      print("bleStateStream:$event");
    });
    subscription3 = _flutterAmzSdkPlugin.scanStream.listen((event) {
      print("scanStream: 111 ${event.length}");
      print("scanStream: 111 ${event.firstOrNull?.bleModelType}");

      List<AMZToy> toys = event;
      setState(() {
        list = toys;
      });
    });
    subscription4 = _flutterAmzSdkPlugin.toyConfigsStream.listen((event) {
      print('111toyConfigsStream: ${event.length}');
      event.forEach(
        (element) {
          print('toyConfigsStream: ${element}');
        },
      );
    });

    _flutterAmzSdkPlugin.setDeveloperToken(token, debug: true);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  TextButton(
                    onPressed: () async {
                      final location = await Permission.location.request();
                      final bluetooth = await Permission.bluetooth.request();
                      final bluetoothConnect = await Permission.bluetoothConnect.request();
                      final bluetoothScan = await Permission.bluetoothScan.request();
                      print(
                          'dashu, bluetooth: $bluetooth, bluetoothConnect: $bluetoothConnect, bluetoothScan: $bluetoothScan, location: $location');
                    },
                    child: const Text('获取蓝牙权限'),
                  ),
                  TextButton(
                    onPressed: () async {
                      _flutterAmzSdkPlugin.checkBlueToothStatus();
                    },
                    child: const Text('获取蓝牙服务权限'),
                  ),
                  TextButton(
                    onPressed: () {
                      _flutterAmzSdkPlugin.searchToys();
                    },
                    child: const Text('searchToys'),
                  ),
                  TextButton(
                    onPressed: () => _flutterAmzSdkPlugin.stopSearching(),
                    child: const Text('stopSearching'),
                  ),
                  TextButton(
                    onPressed: () {
                      if (mAMZToy == null) {
                        showToast('mAMZToy is null');
                        return;
                      }
                      _flutterAmzSdkPlugin.connectToy(mAMZToy!.toyId).listen((event) {
                        print("connectedStream:$event");
                      });
                    },
                    child: const Text('connectToy'),
                  ),
                  TextButton(
                    onPressed: () => _flutterAmzSdkPlugin.disconnect(mAMZToy?.toyId ?? ''),
                    child: const Text('disconnect'),
                  ),
                  TextButton(
                    onPressed: () {
                      if (mAMZToy == null) return;
                      _flutterAmzSdkPlugin
                          .sendCommand(mAMZToy!.toyId, AMZCommandType.COMMON.value, level: 80, levels: [80, 0, 0]);
                    },
                    child: const Text('sendCommand'),
                  ),
                ],
              ),
              Expanded(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: list.length,
                  itemBuilder: (context, index) {
                    final toy = list[index];
                    return TextButton(
                      onPressed: () async {
                        mAMZToy = toy;
                        if (toy.toyId.isEmpty) return;
                        if (await _flutterAmzSdkPlugin.isConnected(toy.toyId)) {
                          Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) => ToyDetailPage(amzToy: toy)));
                          return;
                        }
                        _flutterAmzSdkPlugin.connectToy(toy.toyId).listen((AMZToyStateModel event) {
                          print("connectedStream:$event");
                          showToast('已连接');
                          if (event.state == AMZToyState.stateConnected) {
                            Navigator.of(context)
                                .push(MaterialPageRoute(builder: (context) => ToyDetailPage(amzToy: toy)));
                          }
                        });
                      },
                      child: Text('${toy.bleModelType.name}-${toy.deviceName}-${toy.toyId}',
                          style: const TextStyle(color: Colors.red)),
                    );
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  [@override](/user/override)
  void dispose() {
    super.dispose();
    subscription.cancel();
    subscription1.cancel();
    subscription2.cancel();
    subscription3.cancel();
    subscription4.cancel();
  }

  void showToast(String msg) {
    Fluttertoast.showToast(msg: msg);
  }
}

更多关于Flutter亚马逊服务集成插件flutter_amz_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter亚马逊服务集成插件flutter_amz_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中集成亚马逊服务(如Amazon S3、Amazon Cognito、Amazon DynamoDB等),你可以使用一些现有的插件,如 flutter_amazon_s3amazon_cognito_identity_dart 等。然而,flutter_amz_sdk 并不是一个广为人知的官方或社区插件,因此你可能需要自行开发或寻找其他替代方案。

如果你想使用亚马逊的AWS服务,以下是一些常见的插件和方法:


1. 使用 amazon_cognito_identity_dart 集成 Amazon Cognito

Amazon Cognito 是用于用户身份验证和管理的服务。你可以使用 amazon_cognito_identity_dart 插件来实现用户注册、登录和管理。

步骤:

  • 添加依赖到 pubspec.yaml

    dependencies:
      amazon_cognito_identity_dart: ^2.0.0
    
  • 初始化 Cognito:

    import 'package:amazon_cognito_identity_dart_2/cognito.dart';
    
    final userPool = CognitoUserPool(
      'YOUR_USER_POOL_ID',
      'YOUR_CLIENT_ID',
    );
    
    final cognitoUser = CognitoUser('username', userPool);
    
  • 用户登录:

    final authDetails = AuthenticationDetails(
      username: 'username',
      password: 'password',
    );
    
    try {
      final session = await cognitoUser.authenticateUser(authDetails);
      print('Login successful: ${session.accessToken.jwtToken}');
    } catch (e) {
      print('Login failed: $e');
    }
    

2. 使用 flutter_amazon_s3 集成 Amazon S3

Amazon S3 是用于存储和检索文件的云存储服务。你可以使用 flutter_amazon_s3 插件来上传和下载文件。

步骤:

  • 添加依赖到 pubspec.yaml

    dependencies:
      flutter_amazon_s3: ^1.0.0
    
  • 上传文件到 S3:

    import 'package:flutter_amazon_s3/flutter_amazon_s3.dart';
    
    final filePath = '/path/to/your/file.txt';
    final bucketName = 'your-bucket-name';
    final region = 'us-east-1'; // 你的 S3 区域
    
    try {
      final response = await FlutterAmazonS3.uploadFile(
        filePath: filePath,
        bucketName: bucketName,
        region: region,
        accessKey: 'YOUR_ACCESS_KEY',
        secretKey: 'YOUR_SECRET_KEY',
      );
      print('File uploaded: ${response.url}');
    } catch (e) {
      print('Upload failed: $e');
    }
    

3. 使用 aws_common 集成其他 AWS 服务

aws_common 是一个通用的 AWS SDK,支持多种 AWS 服务(如 DynamoDB、SQS、SNS 等)。

步骤:

  • 添加依赖到 pubspec.yaml

    dependencies:
      aws_common: ^1.0.0
    
  • 初始化 AWS 客户端:

    import 'package:aws_common/aws_common.dart';
    
    final awsClient = AwsClient(
      region: 'us-east-1',
      credentials: AwsCredentials('YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY'),
    );
    
  • 使用 DynamoDB:

    final dynamoDb = awsClient.dynamoDb;
    final response = await dynamoDb.scan(
      tableName: 'your-table-name',
    );
    print('DynamoDB scan result: ${response.items}');
    

4. 自定义集成

如果以上插件不能满足你的需求,你可以直接使用 AWS 官方的 REST API 或 SDK,通过 HTTP 请求与 AWS 服务交互。

示例:

  • 使用 http 包发送请求:
    import 'package:http/http.dart' as http;
    
    final url = Uri.parse('https://s3.amazonaws.com/your-bucket-name/your-file');
    final response = await http.get(url, headers: {
      'Authorization': 'AWS YOUR_ACCESS_KEY:YOUR_SIGNATURE',
    });
    
    if (response.statusCode == 200) {
      print('File content: ${response.body}');
    } else {
      print('Failed to fetch file: ${response.statusCode}');
    }
回到顶部