- hai, i really dont know how to call function beacon from other page to used at main page. i mean after i open app it do not need to click page beacon to run function beacon… And the problem is, i dont know what a keywork to search in internet to solve my problem.
- Want use beacon page at the main page
- What have I tried so far - i dont know what keyword to google. thank you
- Here’s the minimum code you would need to reproduce the problem -
Beacon file-
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:smart_campus/mainpage/example.dart';
import 'package:flutter/services.dart';
import 'package:flutter_beacon/flutter_beacon.dart';
import 'package:smart_campus/level16.dart';
class BeaconTag {
String major;
String minor;
String name;
BeaconTag(this.major, this.minor, this.name);
@override
String toString() {
return '{ ${this.major}, ${this.minor}, ${this.name} }';
}
}
class BeaconWidget extends StatefulWidget {
@override
_BeaconWidgetState createState() => _BeaconWidgetState();
}
class _BeaconWidgetState extends State<BeaconWidget>
with WidgetsBindingObserver {
final StreamController<BluetoothState> streamController = StreamController();
StreamSubscription<BluetoothState> _streamBluetooth;
StreamSubscription<RangingResult> _streamRanging;
final _regionBeacons = <Region, List<Beacon>>{};
final _beacons = <Beacon>[];
bool authorizationStatusOk = false;
bool locationServiceEnabled = false;
bool bluetoothEnabled = false;
final List<BeaconTag> _beaconTags = <BeaconTag>[
BeaconTag('1000', '1', 'Pejabat Rektor'),
BeaconTag('1000', '2', 'Kolej'),
BeaconTag('1000', '3', 'Level 16 KBM'),
BeaconTag('1000', '9', 'Lobby'),
];
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
/**
* ask for permission when user open this widget
*/
if (!authorizationStatusOk) {
flutterBeacon.requestAuthorization;
}
listeningState();
}
listeningState() async {
print('Listening to bluetooth state listeningState()');
_streamBluetooth = flutterBeacon
.bluetoothStateChanged()
.listen((BluetoothState state) async {
print('BluetoothState = $state');
streamController.add(state);
switch (state) {
case BluetoothState.stateOn:
initScanBeacon();
break;
case BluetoothState.stateOff:
await pauseScanBeacon();
await checkAllRequirements();
break;
}
});
}
checkAllRequirements() async {
final bluetoothState = await flutterBeacon.bluetoothState;
final bluetoothEnabled = bluetoothState == BluetoothState.stateOn;
final authorizationStatus = await flutterBeacon.authorizationStatus;
final authorizationStatusOk =
authorizationStatus == AuthorizationStatus.allowed ||
authorizationStatus == AuthorizationStatus.always;
final locationServiceEnabled =
await flutterBeacon.checkLocationServicesIfEnabled;
setState(() {
this.authorizationStatusOk = authorizationStatusOk;
this.locationServiceEnabled = locationServiceEnabled;
this.bluetoothEnabled = bluetoothEnabled;
});
}
initScanBeacon() async {
await flutterBeacon.initializeScanning;
await checkAllRequirements();
if (!authorizationStatusOk ||
!locationServiceEnabled ||
!bluetoothEnabled) {
print('RETURNED, authorizationStatusOk=$authorizationStatusOk, '
'locationServiceEnabled=$locationServiceEnabled, '
'bluetoothEnabled=$bluetoothEnabled');
return;
}
final regions = <Region>[
Region(
identifier: 'UiTM',
proximityUUID: 'b9407f30-f5f8-466e-aff9-25556b57fe6d',
),
];
if (_streamRanging != null) {
if (_streamRanging.isPaused) {
_streamRanging.resume();
return;
}
}
_streamRanging =
flutterBeacon.ranging(regions).listen((RangingResult result) {
// print(result);
if (result != null && mounted) {
setState(() {
_regionBeacons[result.region] = result.beacons;
_beacons.clear();
_regionBeacons.values.forEach((list) {
_beacons.addAll(list);
});
_beacons.sort(_compareParameters);
});
}
});
}
pauseScanBeacon() async {
_streamRanging?.pause();
if (_beacons.isNotEmpty) {
setState(() {
_beacons.clear();
});
}
}
int _compareParameters(Beacon a, Beacon b) {
int compare = a.proximityUUID.compareTo(b.proximityUUID);
if (compare == 0) {
compare = a.accuracy.compareTo(b.accuracy);
}
// if (compare == 0) {
// compare = a.accuracy.compareTo(b.accuracy);
// }
return compare;
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
print('AppLifecycleState = $state');
if (state == AppLifecycleState.resumed) {
if (_streamBluetooth != null && _streamBluetooth.isPaused) {
_streamBluetooth.resume();
}
await checkAllRequirements();
if (authorizationStatusOk && locationServiceEnabled && bluetoothEnabled) {
await initScanBeacon();
} else {
await pauseScanBeacon();
await checkAllRequirements();
}
} else if (state == AppLifecycleState.paused) {
_streamBluetooth?.pause();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
streamController?.close();
_streamRanging?.cancel();
_streamBluetooth?.cancel();
flutterBeacon.close;
super.dispose();
}
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
if (!authorizationStatusOk)
IconButton(
icon: Icon(Icons.portable_wifi_off),
color: Colors.red,
onPressed: () async {
await flutterBeacon.requestAuthorization;
}),
if (!locationServiceEnabled)
IconButton(
icon: Icon(Icons.location_off),
color: Colors.red,
onPressed: () async {
if (Platform.isAndroid) {
await flutterBeacon.openLocationSettings;
} else if (Platform.isIOS) {}
}),
StreamBuilder<BluetoothState>(
builder: (context, snapshot) {
if (snapshot.hasData) {
final state = snapshot.data;
if (state == BluetoothState.stateOn) {
return IconButton(
icon: Icon(Icons.bluetooth_connected),
onPressed: () {},
color: Colors.lightBlueAccent,
);
}
if (state == BluetoothState.stateOff) {
return IconButton(
icon: Icon(Icons.bluetooth),
onPressed: () async {
if (Platform.isAndroid) {
try {
await flutterBeacon.openBluetoothSettings;
} on PlatformException catch (e) {
print(e);
}
} else if (Platform.isIOS) {}
},
color: Colors.red,
);
}
return IconButton(
icon: Icon(Icons.bluetooth_disabled),
onPressed: () {},
color: Colors.grey,
);
}
return SizedBox.shrink();
},
stream: streamController.stream,
initialData: BluetoothState.stateUnknown,
),
],
),
_beacons == null || _beacons.isEmpty
? Center(child: CircularProgressIndicator())
: Expanded(
child: ListView(
children: ListTile.divideTiles(
context: context,
tiles: _beacons.map((beacon) {
BeaconTag _beaconTag = _beaconTags
.where((b) =>
b.major.contains(beacon.major.toString()))
.where((b) =>
b.minor.contains(beacon.minor.toString()))
.first;
return GestureDetector(
child: Card(
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'${beacon.accuracy}',
style: TextStyle(
fontSize: 80.0,
color: Colors.deepPurple,
),
),
Text('Meter')
],
),
),
Text(
_beaconTag.name,
style: TextStyle(fontSize: 30.0),
)
],
)
),
onTap: () {
String x = _beaconTag.name;
if (x == 'Level 16 KBM'){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Kbm()),
);
}
},
);
// return Card(
// child: Row(
// children: <Widget>[
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
// children: <Widget>[
// Text(
// '${beacon.accuracy}',
// style: TextStyle(
// fontSize: 80.0,
// color: Colors.deepPurple,
// ),
// ),
// Text('Meter')
// ],
// ),
// ),
// Text(
// _beaconTag.name,
// style: TextStyle(fontSize: 30.0),
// )
// ],
// ));
// return ListTile(
// title: Text(beacon.proximityUUID),
// subtitle: new Row(
// mainAxisSize: MainAxisSize.max,
// children: <Widget>[
// Flexible(
// child: Text(
// 'Major: ${beacon.major}\nMinor: ${beacon.minor}',
// style: TextStyle(fontSize: 13.0)),
// flex: 1,
// fit: FlexFit.tight),
// Flexible(
// child: Text(
// 'Accuracy: ${beacon.accuracy}m\nRSSI: ${beacon.rssi}',
// style: TextStyle(fontSize: 13.0)),
// flex: 2,
// fit: FlexFit.tight)
// ],
// ),
// );
})).toList(),
),
)
],
),
);
}
}
main page file that i want to call beacon—
import 'package:bubble_bottom_bar/bubble_bottom_bar.dart';
import 'package:flutter/painting.dart';
import 'package:smart_campus/login.dart';
import 'package:smart_campus/mainpage/beacon.dart';
import 'package:smart_campus/mainpage/campus.dart';
import 'package:smart_campus/mainpage/example.dart';
import 'package:smart_campus/mainpage/example_background.dart';
import 'package:smart_campus/mainpage/menu.dart';
import 'package:smart_campus/trhea_main.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'iCampus',
theme: ThemeData(
primarySwatch: Colors.deepPurple,
),
home: MyHomePage(title: 'UiTM iCampus'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int currentIndex;
@override
void initState() {
// TODO: implement initState
super.initState();
currentIndex = 0;
}
void changePage(int index) {
setState(() {
currentIndex = index;
});
}
final List<Widget> _children = [
ExampleBackgroundWidget(),
ExampleWidget(),
BeaconWidget(),
CampusWidget(),
MenuWidget(),
];
final List<Color> _bgColor = [
Colors.white,
Colors.red,
Colors.grey[40],
Colors.grey[40],
Colors.grey[40],
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: _bgColor[currentIndex],
extendBody: true,
appBar: AppBar(
title: Image.asset('assets/images/iCampusWhiteSPNG.png',
fit: BoxFit.fitWidth,
height: 45.0 ,),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.person),
iconSize: 30.0,
tooltip: 'Login',
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage()),);
},)
],
),
body: _children[currentIndex],
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
currentIndex = 4;
});
},
child: Icon(Icons.apps),
backgroundColor: Colors.red,
),
floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
bottomNavigationBar: BubbleBottomBar(
backgroundColor: Colors.deepPurple,
hasNotch: true,
fabLocation: BubbleBottomBarFabLocation.end,
opacity: .2,
currentIndex: currentIndex==4?0:currentIndex,
onTap: changePage,
borderRadius: BorderRadius.vertical(
top: Radius.circular(
16)), //border radius doesn't work when the notch is enabled.
elevation: 8,
items: <BubbleBottomBarItem>[
BubbleBottomBarItem(
backgroundColor: Colors.white,
icon: Icon(
Icons.announcement,
color: Colors.white,
),
activeIcon: Icon(
Icons.announcement,
color: Colors.white,
),
title: Text("News")),
BubbleBottomBarItem(
backgroundColor: Colors.white,
icon: Icon(
Icons.school,
color: Colors.white,
),
activeIcon: Icon(
Icons.school,
color: Colors.white,
),
title: Text("Blank")),
BubbleBottomBarItem(
backgroundColor: Colors.white,
icon: Icon(
Icons.wifi_tethering,
color: Colors.white,
),
activeIcon: Icon(
Icons.wifi_tethering,
color: Colors.white,
),
title: Text("Beacon")),
BubbleBottomBarItem(
backgroundColor: Colors.white,
icon: Icon(
Icons.business,
color: Colors.white,
),
activeIcon: Icon(
Icons.business,
color: Colors.white,
),
title: Text("Campus"))
],
),
);
}
}```