Untitled

mail@pastecode.io avatar
unknown
dart
a year ago
1.7 kB
2
Indexable
Never
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Blue Plus Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Blue Plus Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  Future<void> startScan() async {
    await FlutterBluePlus.startScan(timeout: Duration(seconds: 4));
  }

  @override
  void initState() {
    startScan();
    super.initState();
  }

  @override
  void dispose() {
    FlutterBluePlus.stopScan();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title!),
        ),
        body: StreamBuilder<List<ScanResult>>(
            stream: FlutterBluePlus.scanResults,
            initialData: [],
            builder: (c, snapshot) => ListView(
              children: snapshot.data!
                  .map(
                    (r) => ListTile(
                      title: Text(
                          r.device.localName == '' ? 'Unknown device' : r.device.localName! ),
                      subtitle: Text("RSSI: ${r.rssi.toString()}"),
                    ),
                  )
                  .toList(),
            ),
        ),
    );
  }
}