flutter_ttc_ble 0.0.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 45

flutter_ttc_ble #

Android Bluetooth Low Energy Flutter plugin.

Getting Started #

This project is a starting point for a Flutter plug-in package, a specialized package that includes platform-specific implementation code for Android and/or iOS.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

0.0.1 #

  • TODO: Describe initial release.

0.0.2 #

  • 增加数据发送结果的回调;
  • FlutterTtcBle增加writeCharacteristic()方法。

example/lib/main.dart

import 'dart:async';
import 'dart:typed_data';

import 'package:convert/convert.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ttc_ble/flutter_ttc_ble.dart';

import 'communication.dart';

void main() => runApp(MyApp());

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

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  List<BLEDevice> _dataList = <BLEDevice>[];

  @override
  void initState() {
    super.initState();
    print('main -> initState()');
    WidgetsBinding.instance.addObserver(this);

    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    //TODO BLE 插件初始化
    FlutterTtcBle.init();

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }

  @override
  void didChangeDependencies() {
    print('main -> didChangeDependencies()');
    super.didChangeDependencies();
  }

  @override
  void didUpdateWidget(MyApp oldWidget) {
    //当树rebuid的时候会调用该方法
    print('main -> didUpdateWidget()');
    super.didUpdateWidget(oldWidget);
  }

  @override
  void deactivate() {
    //当State对象从树中被移除时,会调用此回调。
    print('main -> deactivate()');
    super.deactivate();
  }

  @override
  void dispose() {
    //当State对象从树中被永久移除时调用;通常在此回调中释放资源。
    print('main -> dispose()');
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  //Flutter生命周期:https://blog.csdn.net/brycegao321/article/details/86583223
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print('main -> didChangeAppLifecycleState() - state=$state');
    super.didChangeAppLifecycleState(state);
  }

  @override
  Widget build(BuildContext context) {
    //print('main -> build()');
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter BLE Demo V1.0'),
        ),
        body: RefreshIndicator(
          onRefresh: _refresh,
          child: ListView.builder(
            itemCount: _dataList.length,
            itemBuilder: (context, index) {
              return _buildRow(_dataList[index]);
            },
          ),
        ),
      ),
    );
  }

  ///下拉刷新(扫描设备)
  Future<Null> _refresh() async {
    setState(() {
      _dataList.clear();
    });

    FlutterTtcBle.startLeScan((device) {
      setState(() {
        //刷新UI要在setState()方法内进行
        //为了防止列表中设备重复,这里判断一下
        if (!_dataList.contains(device)) _dataList.add(device);
      });
    });

    await Future.delayed(Duration(seconds: 5), () {
      print('refresh() - delayed 5s');
      setState(() {
        //
      });
    });
  }

  ///加载列表项
  Widget _buildRow(BLEDevice device) {
    // 这里使用 Builder 避免异常:Navigator operation requested with a context that does not include a Navigator.
    // 参考 https://blog.csdn.net/nimeghbia/article/details/84388725

    return Builder(
      builder: (context) => new ListTile(
            title: new Text(
              device.name != null ? device.name : "Unknown Device",
            ),
            subtitle: new Text(
              '${device.deviceId}'
                  '\nAdvertisData=${_advertisDataToString(device.advertisData)}'
                  '\nServiceUUIDs=${device.advertisServiceUUIDs}'
                  '\nServiceData=${_serviceDataToString(device.serviceData)}',
            ),
            onTap: () {
              _toCommPage(context, device);
            },
          ),
    );
  }

  String _advertisDataToString(Uint8List advertisData) {
    return advertisData == null ? "" : hex.encode(advertisData);
  }

  String _serviceDataToString(Map<String, Uint8List> serviceData) {
    StringBuffer sb = StringBuffer('{');
    int i = 0;
    serviceData.forEach((uuid, data) => (String uuid, Uint8List data) {
          sb.write("$uuid: ${hex.encode(data)}");
          if (i < serviceData.length - 1) {
            sb.write(', ');
          }
          i++;
        });
    sb.write('}');
    return sb.toString();
  }

  ///跳转到数据交互页面
  void _toCommPage(BuildContext context, BLEDevice device) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (BuildContext context) => CommPage(device)),
    );

    print('从数据交互页面返回 $result');

    ///这是在页面底部显示一个弹出提示
    //Scaffold.of(context).showSnackBar(SnackBar(content: Text(result)));
    //TODO 监听平台消息
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_ttc_ble: ^0.0.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_ttc_ble/flutter_ttc_ble.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
0
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
74
Overall:
Weighted score of the above. [more]
45
Learn more about scoring.

We analyzed this package on Apr 8, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Health suggestions

Fix lib/flutter_ttc_ble.dart. (-0.50 points)

Analysis of lib/flutter_ttc_ble.dart reported 1 hint:

line 29 col 37: This function has a return type of 'Future', but doesn't end with a return statement.

Maintenance suggestions

The package description is too short. (-11 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Homepage URL is insecure. (-5 points)

Update the homepage field and use a secure (https) URL.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.68.0 <3.0.0
convert ^2.1.1 2.1.1
flutter 0.0.0
Transitive dependencies
charcode 1.1.3
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8