expetion error

This commit is contained in:
Thomas Atkins 2021-04-10 21:52:37 -05:00
parent dbc0f84d58
commit 79ecebf86a
6 changed files with 191 additions and 125 deletions

View File

@ -1,21 +1,22 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:loc_chain_app/util/bluetooth.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:loc_chain_app/widgets/navbar.dart'; import 'package:loc_chain_app/widgets/navbar.dart';
import 'dart:math'; import 'package:flutter_udid/flutter_udid.dart';
void main() async { void main() async {
runApp(App()); runApp(App());
final prefs = await SharedPreferences.getInstance(); (await SharedPreferences.getInstance())
final userName = prefs.getString('userName') ?? '0'; .setString('userName', await FlutterUdid.consistentUdid);
if (userName == '0') {
prefs.setString('id', Random().nextInt(10000).toString());
}
} }
class App extends StatelessWidget { class App extends StatelessWidget {
// This widget is the root of your application. // This widget is the root of your application.
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Connect.stop();
Connect.start();
return MaterialApp( return MaterialApp(
title: 'Flutter Demo', title: 'Flutter Demo',
theme: ThemeData( theme: ThemeData(

View File

@ -4,6 +4,7 @@ import 'dart:typed_data';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:nearby_connections/nearby_connections.dart'; import 'package:nearby_connections/nearby_connections.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -16,7 +17,7 @@ class BluetoothPage extends StatefulWidget {
} }
class _BluetoothPageState extends State<BluetoothPage> { class _BluetoothPageState extends State<BluetoothPage> {
// final String id = getId(); final Future<String> _id = FlutterUdid.consistentUdid;
// String getId() => // String getId() =>
// SharedPreferences.getInstance().then((s) => s.getString('id') ?? '0'); // SharedPreferences.getInstance().then((s) => s.getString('id') ?? '0');
@ -26,18 +27,21 @@ class _BluetoothPageState extends State<BluetoothPage> {
appBar: AppBar( appBar: AppBar(
title: Text(widget.title), title: Text(widget.title),
), ),
body: Center( body: FutureBuilder<String>(
child: ElevatedButton( future: _id, // a previously-obtained Future<String> or null
child: Text("GetID"), builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
onPressed: () async { String content = "Loading id...";
final prefs = await SharedPreferences.getInstance(); if (snapshot.hasData) {
final userName = prefs.getString('userName'); content = "ID: ${snapshot.data!}";
}
ScaffoldMessenger.of(context) return ListView(
.showSnackBar(SnackBar(content: Text("Id is $userName"))); children: <Widget>[
}, Container(
), child: Text(content),
), ),
],
);
}),
); );
} }

View File

@ -1,4 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:loc_chain_app/util/bluetooth.dart';
import 'package:loc_chain_app/util/transaction_manager.dart';
class HomePage extends StatefulWidget { class HomePage extends StatefulWidget {
HomePage({Key? key, required this.title}) : super(key: key); HomePage({Key? key, required this.title}) : super(key: key);
@ -9,16 +12,16 @@ class HomePage extends StatefulWidget {
} }
class _HomePageState extends State<HomePage> { class _HomePageState extends State<HomePage> {
int _counter = 0; final Future<String> _id = FlutterUdid.consistentUdid;
Connect connector = Connect();
Map<String, Transaction> transactionMap = Map();
// String getId() =>
// SharedPreferences.getInstance().then((s) => s.getString('id') ?? '0');
void _incrementCounter() { void refreshTransactions() {
setState(() { setState(() {
// This call to setState tells the Flutter framework that something has transactionMap = Connect.transactionMap;
// changed in this State, which causes it to rerun the build method below Connect.context = context;
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
}); });
} }
@ -28,25 +31,51 @@ class _HomePageState extends State<HomePage> {
appBar: AppBar( appBar: AppBar(
title: Text(widget.title), title: Text(widget.title),
), ),
body: Center( body: FutureBuilder<String>(
child: Column( future: _id, // a previously-obtained Future<String> or null
mainAxisAlignment: MainAxisAlignment.center, builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
String content = "Loading id...";
if (snapshot.hasData) {
content = "ID: ${snapshot.data!}";
}
List<Card> transactions = List.generate(
transactionMap.length,
(index) {
Transaction t = transactionMap.values.elementAt(index);
return Card(
child: Row(
children: [Text(t.hash), Text(t.pubKey)],
),
);
},
);
return ListView(
children: <Widget>[ children: <Widget>[
Text( Container(
'You have pushed the button this many times:', child: Text(content),
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
), ),
] +
transactions,
);
}),
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter, onPressed: () {
tooltip: 'Increment', refreshTransactions();
child: Icon(Icons.add), try {
Connect.stop();
Connect.start();
} catch (e) {
print(e);
}
},
child: Icon(Icons.refresh_sharp),
), ),
); );
} }
void showSnackbar(dynamic a) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(a.toString()),
));
}
} }

View File

@ -1,8 +1,7 @@
import 'dart:io';
import 'dart:math';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:nearby_connections/nearby_connections.dart'; import 'package:nearby_connections/nearby_connections.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -11,20 +10,15 @@ import 'package:loc_chain_app/util/keyfile_manager.dart';
import 'package:loc_chain_app/util/transaction_manager.dart'; import 'package:loc_chain_app/util/transaction_manager.dart';
class Connect { class Connect {
final serviceId = "com.yourdomain.appname"; static final serviceId = "com.yourdomain.appname";
final Strategy strategy = Strategy.P2P_STAR; static final Strategy strategy = Strategy.P2P_STAR;
late final _userName; static String _userName = "";
final BuildContext? context; static BuildContext? context;
Map<String, ConnectionInfo> endpointMap = Map(); static Map<String, ConnectionInfo> endpointMap = Map();
Map<String, Transaction> transactionMap = Map(); static Map<String, Transaction> transactionMap = Map();
Connect({this.context}) { static void showSnackbar(dynamic a) {
SharedPreferences.getInstance()
.then((s) => _userName = s.getString('userName') ?? '0');
}
void showSnackbar(dynamic a) {
if (context == null) { if (context == null) {
return; return;
} }
@ -33,12 +27,18 @@ class Connect {
)); ));
} }
void startConnect() async { static void stop() {
Nearby().stopAdvertising();
Nearby().stopDiscovery();
Nearby().stopAllEndpoints();
}
static void start() async {
_userName = await FlutterUdid.consistentUdid;
// final prefs = await SharedPreferences.getInstance(); // final prefs = await SharedPreferences.getInstance();
// final userName = prefs.getString('userName') ?? " "; // final userName = prefs.getString('userName') ?? " ";
try { Nearby().startAdvertising(
bool advertise = await Nearby().startAdvertising(
_userName, _userName,
strategy, strategy,
onConnectionInitiated: onConnectionInit, onConnectionInitiated: onConnectionInit,
@ -50,6 +50,7 @@ class Connect {
} }
// Connected to other device, send combined hash and pub key // Connected to other device, send combined hash and pub key
String str = await Transaction.generateHash(id); String str = await Transaction.generateHash(id);
print(str);
Nearby().sendBytesPayload(id, Uint8List.fromList(str.codeUnits)); Nearby().sendBytesPayload(id, Uint8List.fromList(str.codeUnits));
}, },
onDisconnected: (String id) { onDisconnected: (String id) {
@ -60,9 +61,12 @@ class Connect {
transactionMap.remove(id); transactionMap.remove(id);
}, },
serviceId: serviceId, // uniquely identifies your app serviceId: serviceId, // uniquely identifies your app
); ).catchError((e) {
print(e);
return true;
});
bool discovery = await Nearby().startDiscovery( Nearby().startDiscovery(
_userName, _userName,
strategy, strategy,
onEndpointFound: (String id, String userName, String serviceId) { onEndpointFound: (String id, String userName, String serviceId) {
@ -79,32 +83,44 @@ class Connect {
} }
// Connected to other device, send combined hash and pub key // Connected to other device, send combined hash and pub key
String str = await Transaction.generateHash(id); String str = await Transaction.generateHash(id);
Nearby().sendBytesPayload(id, Uint8List.fromList(str.codeUnits)); Nearby()
.sendBytesPayload(id, Uint8List.fromList(str.codeUnits))
.catchError((e) {
print(e);
});
}, },
onDisconnected: (id) { onDisconnected: (id) {
endpointMap.remove(id); endpointMap.remove(id);
showSnackbar( print(
"Disconnected from: ${endpointMap[id]!.endpointName}, id $id"); "Disconnected from: ${endpointMap[id]!.endpointName}, id $id");
}, },
); ).catchError((e) {
print(e);
return true;
});
}, },
onEndpointLost: (String? id) { onEndpointLost: (String? id) {
//called when an advertiser is lost (only if we weren't connected to it ) //called when an advertiser is lost (only if we weren't connected to it )
}, },
serviceId: serviceId, // uniquely identifies your app serviceId: serviceId, // uniquely identifies your app
); ).catchError((e) {
} catch (exception) { print(e);
// platform exceptions like unable to start bluetooth or insufficient permissions return true;
} });
} }
void onConnectionInit(String otherId, ConnectionInfo info) { static void onConnectionInit(String otherId, ConnectionInfo info) {
print('Connection initialized with $otherId');
// Called whenever a discoverer requests connection // Called whenever a discoverer requests connection
// //
// onConnectionInit // onConnectionInit
if (endpointMap.containsKey(otherId)) { if (endpointMap.containsKey(otherId)) {
print('Connection rejected to/from $otherId');
Nearby().rejectConnection(otherId); Nearby().rejectConnection(otherId);
return;
} }
print('Connection accepted to/from $otherId');
endpointMap[otherId] = info; endpointMap[otherId] = info;
Nearby().acceptConnection( Nearby().acceptConnection(
otherId, otherId,
@ -114,7 +130,7 @@ class Connect {
String str = String.fromCharCodes(payload.bytes!); String str = String.fromCharCodes(payload.bytes!);
var parts = str.split(':'); var parts = str.split(':');
if (parts.length != 2) { if (parts.length != 2) {
showSnackbar("$_otherId invalid payload: $str"); print("$_otherId invalid payload: $str");
return; return;
} }
// Store transaction // Store transaction
@ -123,7 +139,6 @@ class Connect {
transactionMap[_otherId] = transactionMap[_otherId] =
Transaction(hash: combinedHash, pubKey: publicKey); Transaction(hash: combinedHash, pubKey: publicKey);
// sign combined hash with our private key // sign combined hash with our private key
showSnackbar('Received $_otherId payload: $combinedHash');
print('Received $_otherId payload: $combinedHash:$publicKey'); print('Received $_otherId payload: $combinedHash:$publicKey');
// upload hash+otherKey to firebase // upload hash+otherKey to firebase
}, },
@ -131,14 +146,16 @@ class Connect {
if (payloadTransferUpdate.status == PayloadStatus.IN_PROGRESS) { if (payloadTransferUpdate.status == PayloadStatus.IN_PROGRESS) {
print(payloadTransferUpdate.bytesTransferred); print(payloadTransferUpdate.bytesTransferred);
} else if (payloadTransferUpdate.status == PayloadStatus.FAILURE) { } else if (payloadTransferUpdate.status == PayloadStatus.FAILURE) {
print("failed"); print(endid + ": FAILED to transfer file");
showSnackbar(endid + ": FAILED to transfer file");
} else if (payloadTransferUpdate.status == PayloadStatus.SUCCESS) { } else if (payloadTransferUpdate.status == PayloadStatus.SUCCESS) {
showSnackbar( print(
"$endid success, total bytes = ${payloadTransferUpdate.totalBytes}"); "$endid success, total bytes = ${payloadTransferUpdate.totalBytes}");
} }
}, },
); ).catchError((e) {
print(e);
return true;
});
} }
} }

View File

@ -43,6 +43,13 @@ packages:
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.15.0" version: "1.15.0"
crypto:
dependency: transitive
description:
name: crypto
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.1"
cupertino_icons: cupertino_icons:
dependency: "direct main" dependency: "direct main"
description: description:
@ -102,6 +109,13 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
flutter_udid:
dependency: "direct main"
description:
name: flutter_udid
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.0"
flutter_web_plugins: flutter_web_plugins:
dependency: transitive dependency: transitive
description: flutter description: flutter
@ -345,4 +359,4 @@ packages:
version: "0.2.0" version: "0.2.0"
sdks: sdks:
dart: ">=2.12.0 <3.0.0" dart: ">=2.12.0 <3.0.0"
flutter: ">=1.24.0-10" flutter: ">=2.0.0"

View File

@ -33,6 +33,7 @@ dependencies:
fast_rsa: ^1.4.0-nullsafety.4 fast_rsa: ^1.4.0-nullsafety.4
sqflite: ^2.0.0+3 sqflite: ^2.0.0+3
dbcrypt: ^2.0.0 dbcrypt: ^2.0.0
flutter_udid: ^2.0.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: