nearby_connections/example/lib/main.dart

392 lines
15 KiB
Dart
Raw Normal View History

2019-08-11 15:41:40 +00:00
import 'dart:io';
import 'dart:math';
2019-05-11 19:13:34 +00:00
import 'dart:typed_data';
2019-05-10 06:54:05 +00:00
import 'package:flutter/material.dart';
2019-08-11 15:41:40 +00:00
import 'package:image_picker/image_picker.dart';
import 'package:nearby_connections/nearby_connections.dart';
2019-05-10 06:54:05 +00:00
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Nearby Connections example app'),
2019-05-10 06:54:05 +00:00
),
2019-05-10 12:54:38 +00:00
body: Body(),
),
);
}
}
class Body extends StatefulWidget {
@override
_MyBodyState createState() => _MyBodyState();
}
class _MyBodyState extends State<Body> {
2019-08-15 20:20:51 +00:00
final String userName = Random().nextInt(10000).toString();
final Strategy strategy = Strategy.P2P_STAR;
Map<String, ConnectionInfo> endpointMap = Map();
File tempFile; //reference to the file currently being transferred
Map<int, String> map =
Map(); //store filename mapped to corresponding payloadId
2019-05-10 12:54:38 +00:00
@override
Widget build(BuildContext context) {
return Center(
2019-08-15 20:20:51 +00:00
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView(
children: <Widget>[
Text(
"Permissions",
),
2019-08-15 20:20:51 +00:00
Wrap(
children: <Widget>[
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("checkLocationPermission"),
onPressed: () async {
if (await Nearby().checkLocationPermission()) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
2019-08-15 20:20:51 +00:00
content: Text("Location permissions granted :)")));
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content:
Text("Location permissions not granted :(")));
2019-08-15 20:20:51 +00:00
}
},
),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("askLocationPermission"),
onPressed: () async {
if (await Nearby().askLocationPermission()) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Location Permission granted :)")));
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content:
Text("Location permissions not granted :(")));
}
2019-08-15 20:20:51 +00:00
},
),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("checkExternalStoragePermission"),
onPressed: () async {
if (await Nearby().checkExternalStoragePermission()) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
2019-08-15 20:20:51 +00:00
content:
Text("External Storage permissions granted :)")));
2019-08-15 20:20:51 +00:00
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
2019-08-15 20:20:51 +00:00
content: Text(
"External Storage permissions not granted :(")));
}
},
),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("askExternalStoragePermission"),
onPressed: () {
Nearby().askExternalStoragePermission();
},
),
],
),
Divider(),
Text("Location Enabled"),
Wrap(
children: <Widget>[
ElevatedButton(
child: Text("checkLocationEnabled"),
2019-08-15 20:20:51 +00:00
onPressed: () async {
if (await Nearby().checkLocationEnabled()) {
ScaffoldMessenger.of(context).showSnackBar(
2020-04-22 08:49:07 +00:00
SnackBar(content: Text("Location is ON :)")));
} else {
ScaffoldMessenger.of(context).showSnackBar(
2020-04-22 08:49:07 +00:00
SnackBar(content: Text("Location is OFF :(")));
}
},
),
ElevatedButton(
child: Text("enableLocationServices"),
onPressed: () async {
if (await Nearby().enableLocationServices()) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Location Service Enabled :)")));
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content:
Text("Enabling Location Service Failed :(")));
}
2019-08-15 20:20:51 +00:00
},
),
],
),
Divider(),
Text("User Name: " + userName),
Wrap(
children: <Widget>[
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("Start Advertising"),
onPressed: () async {
try {
bool a = await Nearby().startAdvertising(
userName,
strategy,
onConnectionInitiated: onConnectionInit,
2019-08-15 20:20:51 +00:00
onConnectionResult: (id, status) {
showSnackbar(status);
},
onDisconnected: (id) {
showSnackbar(
"Disconnected: ${endpointMap[id].endpointName}, id $id");
setState(() {
endpointMap.remove(id);
});
2019-08-15 20:20:51 +00:00
},
);
showSnackbar("ADVERTISING: " + a.toString());
2019-08-15 20:20:51 +00:00
} catch (exception) {
showSnackbar(exception);
}
},
),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("Stop Advertising"),
onPressed: () async {
await Nearby().stopAdvertising();
},
),
],
),
Wrap(
children: <Widget>[
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("Start Discovery"),
onPressed: () async {
try {
bool a = await Nearby().startDiscovery(
userName,
strategy,
onEndpointFound: (id, name, serviceId) {
// show sheet automatically to request connection
2019-08-15 20:20:51 +00:00
showModalBottomSheet(
context: context,
builder: (builder) {
return Center(
child: Column(
children: <Widget>[
Text("id: " + id),
Text("Name: " + name),
Text("ServiceId: " + serviceId),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("Request Connection"),
onPressed: () {
Navigator.pop(context);
Nearby().requestConnection(
userName,
id,
onConnectionInitiated: (id, info) {
onConnectionInit(id, info);
2019-08-15 20:20:51 +00:00
},
onConnectionResult: (id, status) {
showSnackbar(status);
},
onDisconnected: (id) {
setState(() {
endpointMap.remove(id);
});
showSnackbar(
"Disconnected from: ${endpointMap[id].endpointName}, id $id");
2019-08-15 20:20:51 +00:00
},
);
},
),
],
),
);
},
);
},
onEndpointLost: (id) {
showSnackbar(
"Lost discovered Endpoint: ${endpointMap[id].endpointName}, id $id");
2019-08-15 20:20:51 +00:00
},
);
showSnackbar("DISCOVERING: " + a.toString());
2019-08-15 20:20:51 +00:00
} catch (e) {
showSnackbar(e);
}
},
),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("Stop Discovery"),
onPressed: () async {
await Nearby().stopDiscovery();
},
),
],
),
Text("Number of connected devices: ${endpointMap.length}"),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("Stop All Endpoints"),
onPressed: () async {
await Nearby().stopAllEndpoints();
setState(() {
endpointMap.clear();
});
2019-08-15 20:20:51 +00:00
},
),
Divider(),
Text(
"Sending Data",
),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("Send Random Bytes Payload"),
onPressed: () async {
endpointMap.forEach((key, value) {
String a = Random().nextInt(100).toString();
showSnackbar("Sending $a to ${value.endpointName}, id: $key");
Nearby()
.sendBytesPayload(key, Uint8List.fromList(a.codeUnits));
});
2019-08-15 20:20:51 +00:00
},
),
ElevatedButton(
2019-08-15 20:20:51 +00:00
child: Text("Send File Payload"),
onPressed: () async {
PickedFile file =
await ImagePicker().getImage(source: ImageSource.gallery);
2019-08-11 15:41:40 +00:00
2019-08-15 20:20:51 +00:00
if (file == null) return;
2019-08-11 15:41:40 +00:00
for (MapEntry<String, ConnectionInfo> m
in endpointMap.entries) {
int payloadId =
await Nearby().sendFilePayload(m.key, file.path);
showSnackbar("Sending file to ${m.key}");
Nearby().sendBytesPayload(
m.key,
Uint8List.fromList(
"$payloadId:${file.path.split('/').last}".codeUnits));
}
2019-08-15 20:20:51 +00:00
},
),
],
),
2019-05-10 06:54:05 +00:00
),
);
}
2019-05-11 08:34:12 +00:00
void showSnackbar(dynamic a) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(a.toString()),
));
}
2019-05-11 19:37:58 +00:00
/// Called upon Connection request (on both devices)
/// Both need to accept connection to start sending/receiving
void onConnectionInit(String id, ConnectionInfo info) {
2019-05-11 19:37:58 +00:00
showModalBottomSheet(
context: context,
builder: (builder) {
return Center(
child: Column(
children: <Widget>[
Text("id: " + id),
Text("Token: " + info.authenticationToken),
Text("Name" + info.endpointName),
Text("Incoming: " + info.isIncomingConnection.toString()),
ElevatedButton(
2019-05-11 19:37:58 +00:00
child: Text("Accept Connection"),
onPressed: () {
Navigator.pop(context);
setState(() {
endpointMap[id] = info;
});
2019-05-11 19:37:58 +00:00
Nearby().acceptConnection(
id,
2019-08-15 19:30:35 +00:00
onPayLoadRecieved: (endid, payload) async {
2019-08-11 15:41:40 +00:00
if (payload.type == PayloadType.BYTES) {
2019-08-15 19:30:35 +00:00
String str = String.fromCharCodes(payload.bytes);
showSnackbar(endid + ": " + str);
if (str.contains(':')) {
// used for file payload as file payload is mapped as
// payloadId:filename
int payloadId = int.parse(str.split(':')[0]);
String fileName = (str.split(':')[1]);
if (map.containsKey(payloadId)) {
if (await tempFile.exists()) {
tempFile.rename(
tempFile.parent.path + "/" + fileName);
} else {
showSnackbar("File doesn't exist");
2019-08-15 19:30:35 +00:00
}
} else {
//add to map if not already
map[payloadId] = fileName;
}
}
2019-08-11 15:41:40 +00:00
} else if (payload.type == PayloadType.FILE) {
showSnackbar(endid + ": File transfer started");
2019-08-15 19:30:35 +00:00
tempFile = File(payload.filePath);
2019-08-11 15:41:40 +00:00
}
},
onPayloadTransferUpdate: (endid, payloadTransferUpdate) {
if (payloadTransferUpdate.status ==
PayloadStatus.IN_PROGRESS) {
2019-08-11 15:41:40 +00:00
print(payloadTransferUpdate.bytesTransferred);
} else if (payloadTransferUpdate.status ==
PayloadStatus.FAILURE) {
print("failed");
showSnackbar(endid + ": FAILED to transfer file");
} else if (payloadTransferUpdate.status ==
PayloadStatus.SUCCESS) {
2019-08-15 20:20:51 +00:00
showSnackbar(
"$endid success, total bytes = ${payloadTransferUpdate.totalBytes}");
2019-08-15 19:30:35 +00:00
if (map.containsKey(payloadTransferUpdate.id)) {
//rename the file now
String name = map[payloadTransferUpdate.id];
tempFile.rename(tempFile.parent.path + "/" + name);
} else {
//bytes not received till yet
map[payloadTransferUpdate.id] = "";
}
2019-08-11 15:41:40 +00:00
}
2019-05-11 19:37:58 +00:00
},
);
},
),
ElevatedButton(
2019-05-11 19:37:58 +00:00
child: Text("Reject Connection"),
2019-05-11 20:00:07 +00:00
onPressed: () async {
2019-05-11 19:37:58 +00:00
Navigator.pop(context);
2019-05-11 20:00:07 +00:00
try {
await Nearby().rejectConnection(id);
} catch (e) {
showSnackbar(e);
}
2019-05-11 19:37:58 +00:00
},
),
],
),
);
},
);
}
}