loadingbar not working using getx flutter - flutter

hello I am working on a project using google maps inside it I implemented a loading bar using getx but it's not working I don't know why
here is my map page :
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:helping_hand/StateManagement/BarController.dart';
import 'package:helping_hand/UI/Other/Emergency.dart';
import 'package:list_picker/list_picker.dart';
import '../../StateManagement/MapController.dart';
import '../../drawers/bottomnavbar.dart';
import '../Bottom Navigation/My status.dart';
class Mappage extends StatelessWidget {
Mappage({Key? key}) : super(key: key);
final TextEditingController selectPage = TextEditingController();
final List<String> pageList = ['helps','sitrep','location','emergencies', 'users',];
#override
Widget build(BuildContext context) {
MapController mapcontroller = Get.find();
BarController barController = Get.find();
barController.checkUserData();
return Scaffold(
body: Stack(
children: [
SizedBox(height: MediaQuery.of(context).size.height,
child: SingleChildScrollView(
child: SizedBox(height: MediaQuery.of(context).size.height,width: MediaQuery.of(context).size.width,
child: Column(
children: [
Stack(
children: [
SizedBox(
height: MediaQuery.of(context).size.height,
child: GetBuilder<MapController>(builder: (_)=>GoogleMap(initialCameraPosition:MapController.initial,
mapType: MapType.normal,markers:mapcontroller.markers,
onMapCreated: (GoogleMapController controller){
mapcontroller.completercontrol.complete(controller);
mapcontroller.googleMapController = controller;
},),)
),
Positioned(
top: 50,
height: 60,
width: MediaQuery.of(context).size.width,
child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(width: MediaQuery.of(context).size.width/2,
child: ListPickerField(label:'select', items:pageList,controller:selectPage,)),
ElevatedButton(
style:const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent)) ,
onPressed: () {
if(selectPage.text.isNotEmpty){
mapcontroller.fetchMap(selectPage.text);
}else{
Get.snackbar('error','select a page from dropdown menu');
}
},
child:const Text('Get',style: TextStyle(color: Colors.white),)),
FloatingActionButton(
heroTag: 'btn1',
onPressed:(){
Get.to(()=>Emergency());
},
child: const Icon(Icons.emergency_outlined),
)
],
),
),
Positioned(
bottom: 50,
width: MediaQuery.of(context).size.width,
child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
style:const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent)) ,
onPressed: () {
mapcontroller.googleMapController.dispose();
Get.offAll(()=>const Nav());
},
child:const Text('Go to Dashboard',style: TextStyle(color: Colors.white),)),
FloatingActionButton(
heroTag: 'btn2',
onPressed: () {
mapcontroller.getlatlong();
},
child:const Icon(Icons.location_on,color: Colors.white,)),
],
),
),
],
),
],
),
),
),
),
GetBuilder<MapController>(builder: (_){
if (mapcontroller.isloading == true) {
return Container(
color: Colors.white.withOpacity(0.5),
child: const Center(
child: CircularProgressIndicator(backgroundColor: Colors.redAccent,color: Colors.white,),
),
);
} else {
return const SizedBox.shrink();
}
}),
],
));
}
}
class DocsForMap {
final double lat;
final double long;
final String? desc;
final String title;
final int? uploaddate;
final int? deletetime;
final List<dynamic>? neededSupply;
final List<dynamic>? downloadurl;
DocsForMap(this.desc, this.uploaddate, this.deletetime, this.neededSupply, this.downloadurl,{
required this.lat,
required this.long,
required this.title,
});
}
here is the controller (look at the bottom for function FetchAlerts and loading bar) :
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:helping_hand/UI/Map/Mappage.dart';
class MapController extends GetxController{
String locationmessage = 'currentlocation of user';
late String lat ;
late String long ;
Set<Marker>markers= <Marker>{};
late BitmapDescriptor customIcon;
#override
void onInit() {
// BitmapDescriptor.fromAssetImage(const ImageConfiguration(size: Size(3.5, 3.5)),
// 'assets/undraw/warning.png')
// .then((d) {
// customIcon = d;
// update();
// });
lat = '10.228370';
long ='76.198799';
super.onInit();
}
// make sure to initialize before map loading
late GoogleMapController googleMapController;
final Completer<GoogleMapController> _controller = Completer();
Completer<GoogleMapController> get completercontrol => _controller;
static CameraPosition initial = const CameraPosition(target:LatLng(10.228370,76.198799),zoom: 15);
//lower part
Future<Position> getCurrentLocation() async {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('the location is not enabled');
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error(
'location permissions are permanantly denied, cannot grant acess');
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error(
'location permissions are permanantly denied, cannot grant acess');
}
return await Geolocator.getCurrentPosition();
}
void liveLocation() {
loadingbar();
LocationSettings settings = const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 100,
);
Geolocator.getPositionStream(locationSettings: settings)
.listen((Position position) {
lat = position.latitude.toString();
long = position.longitude.toString();
googleMapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target:LatLng(position.latitude,position.longitude),zoom: 15)));
markers.add(Marker(markerId:const MarkerId('current user location'),position: LatLng(position.latitude,position.longitude)));
update();
});
loadingbaroff();
}
void getlatlong(){
loadingbar();
getCurrentLocation().then((value){
lat = '${value.latitude}';
long = '${value.longitude}';
googleMapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target:LatLng(value.latitude,value.longitude),zoom: 15)));
markers.add(Marker(markerId:const MarkerId('current user location'),position: LatLng(value.latitude,value.longitude)));
update();
if (kDebugMode) {
print(lat);
}
if (kDebugMode) {
print(long);
}
liveLocation();
});
loadingbaroff();
}
void liveLocationToUpload(){
LocationSettings settings = const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 100,
);
Geolocator.getPositionStream(locationSettings: settings)
.listen((Position position) {
lat = position.latitude.toString();
long = position.longitude.toString();
update();
});
}
//MAP PAGE CONTROLLER CONTROLLS ::::::::::::::
List<DocsForMap> docsformap=[];
Future<void> fetchMap(String page)async {
try{
loadingbar();
docsformap.clear();
int unixTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
if (kDebugMode) {
print('inside try catch');
}
if (kDebugMode) {
print(page);
}
final FirebaseFirestore db = FirebaseFirestore.instance;
db.collection("map").doc('maps').collection(page).get().then((querySnapshot) {
for (var document in querySnapshot.docs) {
if(document.data()['deleteTime'] > unixTime){
docsformap.add(DocsForMap(document.data()['description'], document.data()['uploadDate'], document.data()['deleteTime'],
document.data()['needed_supply'], document.data()['downloadUrl'], lat: double.parse(document.data()['lat']),
long: double.parse(document.data()['long']), title:document.data()['title']));
}
}
//adding markers
markers.clear();
for(int i = 0;i<docsformap.length;i++){
markers.add(Marker(markerId: MarkerId('$i'),
position: LatLng(docsformap[i].lat,docsformap[i].long),
infoWindow:InfoWindow(title: docsformap[i].title,snippet: docsformap[i].desc),
// icon:customIcon,
onTap: (){markerBar();}
));
}
for (var element in markers) {
if (kDebugMode) {
print('this is a marker element ${element.infoWindow.snippet}');
}
}
update();
});
}catch(e){
Get.snackbar('error','error while fetching $page');
if (kDebugMode) {
print('error happenddddd :::::::: $e');
}
loadingbaroff();
}
loadingbaroff();
}
bool isloading = false;
void loadingbar() {
print('loading bar called');
isloading = true;
update();
}
void loadingbaroff() {
print('loading bar ended');
isloading = false;
update();
}
bool isMarkerSelected = false;
void markerBar() {
isMarkerSelected = true;
update();
}
void markerBaroff() {
isMarkerSelected = false;
update();
}
}
also if you could tell me instead of giving value through initial variable when map creates, can i create the map with current user location using oninit on mapcontroller ?

Related

Google map camera error : unhandled Exception: MissingPluginException(No implementation found for method camera#animate

This bounty has ended. Answers to this question are eligible for a +50 reputation bounty. Bounty grace period ends in 16 hours.
Abhiram is looking for a canonical answer.
I was implementing google maps in flutter my everything worked fine until I get this error,
The direction flow of the app is : login => Mappage =>dashboard => Mappage
after login, the map page works fine but when going to the dashboard and coming back again to the map page it shows this error :
unhandled Exception: MissingPluginException(No implementation found for method camera#animate on channel plugins.flutter.dev/google_maps_android_0)
I am using the animateCamera method in my code many times but it worked the first time (Mappage after login ) is this because of completer ? please explain
here is my code :
Mappage.dart :
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import '../../StateManagement/MapController.dart';
import '../../drawers/bottomnavbar.dart';
class Mappage extends StatelessWidget {
const Mappage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
MapController mapcontroller = Get.find();
return Scaffold(
body: Stack(
children: [
SizedBox(height: MediaQuery.of(context).size.height,
child: SingleChildScrollView(
child: SizedBox(height: MediaQuery.of(context).size.height,width: MediaQuery.of(context).size.width,
child: Column(
children: [
Stack(
children: [
SizedBox(
height: MediaQuery.of(context).size.height,
child: GetBuilder<MapController>(builder: (_)=>GoogleMap(initialCameraPosition:MapController.initial,
mapType: MapType.normal,markers:mapcontroller.markers,
onMapCreated: (GoogleMapController controller){
mapcontroller.completercontrol.complete(controller);
mapcontroller.googleMapController = controller;
},),)
),
Positioned(
bottom: 50,
width: MediaQuery.of(context).size.width,
child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
style:const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent)) ,
onPressed: () {
Get.offAll(()=>Nav());
},
child:const Text('Go to Dashboard',style: TextStyle(color: Colors.white),)),
FloatingActionButton(
onPressed: () {
mapcontroller.getlatlong();
},
child:const Icon(Icons.location_on,color: Colors.white,)),
],
),
),
],
),
],
),
),
),
),
GetBuilder<MapController>(builder: (_){
if (mapcontroller.isloading == true) {
return Container(
color: Colors.white.withOpacity(0.5),
child: const Center(
child: CircularProgressIndicator(backgroundColor: Colors.redAccent,color: Colors.white,),
),
);
} else {
return const SizedBox.shrink();
}
}),
],
));
}
}
mapcontroller (using getx):
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class MapController extends GetxController{
String locationmessage = 'currentlocation of user';
late String lat ;
late String long ;
Set<Marker>markers={};
#override
void onInit() {
lat = '10.228370';
long ='76.198799';
super.onInit();
}
late GoogleMapController googleMapController;
final Completer<GoogleMapController> _controller = Completer();
Completer<GoogleMapController> get completercontrol => _controller;
static CameraPosition initial = const CameraPosition(target:LatLng(10.228370,76.198799),zoom: 15);
//lower part
Future<Position> getCurrentLocation() async {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('the location is not enabled');
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error(
'location permissions are permanantly denied, cannot grant acess');
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error(
'location permissions are permanantly denied, cannot grant acess');
}
return await Geolocator.getCurrentPosition();
}
void liveLocation() {
loadingbar();
LocationSettings settings = const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 100,
);
Geolocator.getPositionStream(locationSettings: settings)
.listen((Position position) {
lat = position.latitude.toString();
long = position.longitude.toString();
googleMapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target:LatLng(position.latitude,position.longitude),zoom: 15)));
markers.clear();
markers.add(Marker(markerId:const MarkerId('current user location'),position: LatLng(position.latitude,position.longitude)));
update();
});
loadingbaroff();
}
void getlatlong(){
loadingbar();
getCurrentLocation().then((value){
lat = '${value.latitude}';
long = '${value.longitude}';
googleMapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target:LatLng(value.latitude,value.longitude),zoom: 15)));
markers.clear();
markers.add(Marker(markerId:const MarkerId('current user location'),position: LatLng(value.latitude,value.longitude)));
update();
if (kDebugMode) {
print(lat);
}
if (kDebugMode) {
print(long);
}
liveLocation();
});
loadingbaroff();
}
void liveLocationToUpload(){
LocationSettings settings = const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 100,
);
Geolocator.getPositionStream(locationSettings: settings)
.listen((Position position) {
lat = position.latitude.toString();
long = position.longitude.toString();
update();
});
}
//MAP PAGE CONTROLLER CONTROLLS :::::::::::::;
Future<void> fetchMap()async {
//markers.clear();
//markers.add(Marker(markerId:const MarkerId('current user location'),position: LatLng(position.latitude,position.longitude)));
}
bool isloading = false;
void loadingbar() {
isloading = true;
update();
}
void loadingbaroff() {
isloading = false;
update();
}
}
First of all, let's try to isolate the issue. Have you ever tried to navigate to another page different of "dashboard" after being in "Mappage"? Try it and tell me if happens the same problem since you say the problem occurs when you leave "Mappage" and get back to "Mappage".
so after getting all errors and doing flutter clean and pub get I couldn't solve the issue finally I figured it out and it was simple :
In my code, you can see that I used a completer (on the GoogleMap widget and on the map controller ) but that is an outdated approach most of the tutorials still have that code now the right thing to do here is ignore the completer we do not want to use the completer for google maps
instead, just use GoogleMapController only like this
GetBuilder<MapController>(builder: (_)=>GoogleMap(initialCameraPosition:MapController.initial,
mapType: MapType.normal,markers:mapcontroller.markers,
onMapCreated: (GoogleMapController controller){
mapcontroller.markers.clear();
mapcontroller.googleMapController = controller;
mapcontroller.liveLocation();
},),
)
in map controller :
late GoogleMapController googleMapController;
static CameraPosition initial = const CameraPosition(target:LatLng(10.228370,76.198799),zoom: 15);

How convert material page as a dialog box on flutter?

when clicking this mic image then should show this recording material page as a dialog box.
That recording page I want add in this dialog box..
On the recording page, I tried it but that didn't worked.
I tried to change this page like as a dialog box but it didn't work.
dialog box code..
import 'dart:js';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:material_dialogs/material_dialogs.dart';
import 'package:material_dialogs/widgets/buttons/icon_outline_button.dart';
import '../../../../provider/sign_in_provider.dart';
import '../recorder/feature_buttons_view.dart';
String? downloadURL;
List<Reference> references = [];
#override
void initState() {
super.initState();
_onUploadComplete();
}
//snack bar for showing error
showSnackBar(String snackText, Duration d) {
final snackBar = SnackBar(content: Text(snackText), duration: d);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
RecorderDialogScreen(BuildContext context) {
Dialogs.materialDialog(
msg: 'Are you sure ? you can\'t undo this',
color: Colors.white,
context: context,
dialogWidth: kIsWeb ? 0.3 : null,
onClose: (value) => print("returned value is '$value'"),
actions: [
Expanded(
flex: 2,
child: FeatureButtonsView(
onUploadComplete: _onUploadComplete,
),
),
IconsOutlineButton(
onPressed: () {
Navigator.of(context).pop(['Test', 'List']);
},
text: 'Cancel',
iconData: Icons.cancel_outlined,
textStyle: TextStyle(color: Colors.grey),
iconColor: Colors.grey,
),
]);
}
Future<void> _onUploadComplete() async {
final sp = context.read<SignInProvider>();
FirebaseStorage firebaseStorage = FirebaseStorage.instance;
ListResult listResult = await firebaseStorage
.ref()
.child("${sp.uid}/records")
.child("voices")
.list();
setState(() {
references = listResult.items;
});
}
error on dialog box
recording material page code
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kathana/screens/voiceRecord/voiceRecord12/recorder/feature_buttons_view.dart';
import 'package:provider/provider.dart';
import '../../../provider/sign_in_provider.dart';
class Recorder12Screen extends StatefulWidget {
#override
State<Recorder12Screen> createState() => _Recorder12ScreenState();
}
class _Recorder12ScreenState extends State<Recorder12Screen> {
String? downloadURL;
List<Reference> references = [];
#override
void initState() {
super.initState();
_onUploadComplete();
}
//snack bar for showing error
showSnackBar(String snackText, Duration d) {
final snackBar = SnackBar(content: Text(snackText), duration: d);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
#override
Widget build(BuildContext context) {
final sp = context.read<SignInProvider>();
return Scaffold(
body: Column(
children: [
Expanded(
flex: 2,
child: FeatureButtonsView(
onUploadComplete: _onUploadComplete,
),
),
Text(
"${sp.uid}",
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
),
],
),
);
}
Future<void> _onUploadComplete() async {
final sp = context.read<SignInProvider>();
FirebaseStorage firebaseStorage = FirebaseStorage.instance;
ListResult listResult = await firebaseStorage
.ref()
.child("${sp.uid}/records")
.child("voices")
.list();
setState(() {
references = listResult.items;
});
}
}
mic image code
Center(
child: Padding(
padding: const EdgeInsets.only(top: 1),
child: IconButton(
iconSize: 45,
icon: Ink.image(
image: const AssetImage('assets/mic.png'),
),
onPressed: () {
// do something when the button is pressed
RecorderDialogScreen(context);
},
),
),
),
If you are know how to solve it please provide a example.
FeatureButtonsView(onUploadComplete: _onUploadComplete,)
page
import 'dart:io';
import 'package:audioplayers/audioplayers.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_audio_recorder2/flutter_audio_recorder2.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import '../../../../provider/sign_in_provider.dart';
class FeatureButtonsView extends StatefulWidget {
final Function onUploadComplete;
FeatureButtonsView({
Key? key,
required this.onUploadComplete,
}) : super(key: key);
#override
_FeatureButtonsViewState createState() => _FeatureButtonsViewState();
String? userId;
}
class _FeatureButtonsViewState extends State<FeatureButtonsView> {
late bool _isPlaying;
late bool _isUploading;
late bool _isRecorded;
late bool _isRecording;
late AudioPlayer _audioPlayer;
late String _filePath;
late FlutterAudioRecorder2 _audioRecorder;
Future getData() async {
final sp = context.read<SignInProvider>();
sp.getDataFromSharedPreferences();
}
String downloadUrl = '';
Future<void> onsend() async {
//uploading to cloudfirestore
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
final sp = context.read<SignInProvider>();
await firebaseFirestore
.collection("users")
.doc("${sp.uid}")
.collection("reco")
.add({'downloadURL': downloadUrl}).whenComplete(() =>
showSnackBar("Voice uploaded successful", Duration(seconds: 2)));
}
//snackbar for showing error
showSnackBar(String snackText, Duration d) {
final snackBar = SnackBar(content: Text(snackText), duration: d);
}
#override
void initState() {
super.initState();
_isPlaying = false;
_isUploading = false;
_isRecorded = false;
_isRecording = false;
_audioPlayer = AudioPlayer();
final sp = context.read<SignInProvider>();
FirebaseFirestore.instance
.collection("users")
.doc(sp.uid)
.get()
.then((value) {
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return Center(
child: _isRecorded
? _isUploading
? Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: LinearProgressIndicator()),
Text('Uplaoding to Firebase'),
],
)
: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
IconButton(
icon: Icon(Icons.replay),
onPressed: _onRecordAgainButtonPressed,
),
IconButton(
icon: Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
onPressed: _onPlayButtonPressed,
),
IconButton(
icon: Icon(Icons.upload_file),
onPressed: _onFileUploadButtonPressed,
),
],
)
: IconButton(
icon: _isRecording
? Icon(Icons.pause)
: Icon(Icons.fiber_manual_record),
onPressed: _onRecordButtonPressed,
),
);
}
Future<void> _onFileUploadButtonPressed() async {
FirebaseStorage firebaseStorage = FirebaseStorage.instance;
setState(() {
_isUploading = true;
});
try {
final sp = context.read<SignInProvider>();
Reference ref = firebaseStorage.ref().child("${sp.uid}/records1").child(
_filePath.substring(_filePath.lastIndexOf('/'), _filePath.length));
TaskSnapshot uploadedFile = await ref.putFile(File(_filePath));
if (uploadedFile.state == TaskState.success) {
downloadUrl = await ref.getDownloadURL();
}
widget.onUploadComplete();
onsend(); //send downloadURL after get it
} catch (error) {
print('Error occured while uplaoding to Firebase ${error.toString()}');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error occured while uplaoding'),
),
);
} finally {
setState(() {
_isUploading = false;
});
}
}
void _onRecordAgainButtonPressed() {
setState(() {
_isRecorded = false;
});
}
Future<void> _onRecordButtonPressed() async {
if (_isRecording) {
_audioRecorder.stop();
_isRecording = false;
_isRecorded = true;
} else {
_isRecorded = false;
_isRecording = true;
await _startRecording();
}
setState(() {});
}
void _onPlayButtonPressed() {
if (!_isPlaying) {
_isPlaying = true;
_audioPlayer.play(_filePath, isLocal: true);
_audioPlayer.onPlayerCompletion.listen((duration) {
setState(() {
_isPlaying = false;
});
});
} else {
_audioPlayer.pause();
_isPlaying = false;
}
setState(() {});
}
Future<void> _startRecording() async {
final bool? hasRecordingPermission =
await FlutterAudioRecorder2.hasPermissions;
if (hasRecordingPermission ?? false) {
Directory directory = await getApplicationDocumentsDirectory();
String filepath = directory.path +
'/' +
DateTime.now().millisecondsSinceEpoch.toString() +
'.aac';
_audioRecorder =
FlutterAudioRecorder2(filepath, audioFormat: AudioFormat.AAC);
await _audioRecorder.initialized;
_audioRecorder.start();
_filePath = filepath;
setState(() {});
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Center(child: Text('Please enable recording permission'))));
}
}
}

flutter - how to create voice record in popup when click mic image using flutter?

mic image code
Center(
child: Padding(
padding: const EdgeInsets.only(top: 1),
child: IconButton(
iconSize: 45,
icon: Ink.image(
image: const AssetImage('assets/mic.png'),
),
onPressed: () {
// do something when the button is pressed
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Recorder12Screen()),
);
// RecorderDialogScreen(context);
},
),
),
),
when click this mic image I want display voice recording page as a pop up window.
recording page image... my output
But I wanna like this
I my voice recording function has 2 pages
and this
2nd page is then the click pause button then display playback page
both pages I wanna display as pop up windows
1st page
2nd page
1st page code
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kathana/screens/voiceRecord/voiceRecord12/recorder/feature_buttons_view.dart';
import 'package:provider/provider.dart';
import '../../../provider/sign_in_provider.dart';
class Recorder12Screen extends StatefulWidget {
#override
State<Recorder12Screen> createState() => _Recorder12ScreenState();
}
class _Recorder12ScreenState extends State<Recorder12Screen> {
String? downloadURL;
List<Reference> references = [];
#override
void initState() {
super.initState();
_onUploadComplete();
}
//snack bar for showing error
showSnackBar(String snackText, Duration d) {
final snackBar = SnackBar(content: Text(snackText), duration: d);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
#override
Widget build(BuildContext context) {
final sp = context.read<SignInProvider>();
return Scaffold(
body: Column(
children: [
Expanded(
flex: 2,
child: FeatureButtonsView(
onUploadComplete: _onUploadComplete,
),
),
Text(
"${sp.uid}",
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
),
],
),
);
}
Future<void> _onUploadComplete() async {
final sp = context.read<SignInProvider>();
FirebaseStorage firebaseStorage = FirebaseStorage.instance;
ListResult listResult = await firebaseStorage
.ref()
.child("${sp.uid}/records")
.child("voices")
.list();
setState(() {
references = listResult.items;
});
}
}
2nd page code
import 'dart:io';
import 'package:audioplayers/audioplayers.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_audio_recorder2/flutter_audio_recorder2.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import '../../../../provider/sign_in_provider.dart';
class FeatureButtonsView extends StatefulWidget {
final Function onUploadComplete;
FeatureButtonsView({
Key? key,
required this.onUploadComplete,
}) : super(key: key);
#override
_FeatureButtonsViewState createState() => _FeatureButtonsViewState();
String? userId;
}
class _FeatureButtonsViewState extends State<FeatureButtonsView> {
late bool _isPlaying;
late bool _isUploading;
late bool _isRecorded;
late bool _isRecording;
late AudioPlayer _audioPlayer;
late String _filePath;
late FlutterAudioRecorder2 _audioRecorder;
Future getData() async {
final sp = context.read<SignInProvider>();
sp.getDataFromSharedPreferences();
}
String downloadUrl = '';
Future<void> onsend() async {
//uploading to cloudfirestore
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
final sp = context.read<SignInProvider>();
await firebaseFirestore
.collection("users")
.doc("${sp.uid}")
.collection("reco")
.add({'downloadURL': downloadUrl}).whenComplete(() =>
showSnackBar("Voice uploaded successful", Duration(seconds: 2)));
}
//snackbar for showing error
showSnackBar(String snackText, Duration d) {
final snackBar = SnackBar(content: Text(snackText), duration: d);
}
#override
void initState() {
super.initState();
_isPlaying = false;
_isUploading = false;
_isRecorded = false;
_isRecording = false;
_audioPlayer = AudioPlayer();
final sp = context.read<SignInProvider>();
FirebaseFirestore.instance
.collection("users")
.doc(sp.uid)
.get()
.then((value) {
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return Center(
child: _isRecorded
? _isUploading
? Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: LinearProgressIndicator()),
Text('Uplaoding to Firebase'),
],
)
: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
IconButton(
icon: Icon(Icons.replay),
onPressed: _onRecordAgainButtonPressed,
),
IconButton(
icon: Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
onPressed: _onPlayButtonPressed,
),
IconButton(
icon: Icon(Icons.upload_file, color: Colors.green),
onPressed: _onFileUploadButtonPressed,
),
],
)
: IconButton(
icon: _isRecording
? Icon(Icons.pause)
: Icon(Icons.fiber_manual_record),
onPressed: _onRecordButtonPressed,
),
);
}
Future<void> _onFileUploadButtonPressed() async {
FirebaseStorage firebaseStorage = FirebaseStorage.instance;
setState(() {
_isUploading = true;
});
try {
final sp = context.read<SignInProvider>();
Reference ref = firebaseStorage.ref().child("${sp.uid}/records1").child(
_filePath.substring(_filePath.lastIndexOf('/'), _filePath.length));
TaskSnapshot uploadedFile = await ref.putFile(File(_filePath));
if (uploadedFile.state == TaskState.success) {
downloadUrl = await ref.getDownloadURL();
}
widget.onUploadComplete();
onsend(); //send downloadURL after get it
} catch (error) {
print('Error occured while uplaoding to Firebase ${error.toString()}');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error occured while uplaoding'),
),
);
} finally {
setState(() {
_isUploading = false;
});
}
}
void _onRecordAgainButtonPressed() {
setState(() {
_isRecorded = false;
});
}
Future<void> _onRecordButtonPressed() async {
if (_isRecording) {
_audioRecorder.stop();
_isRecording = false;
_isRecorded = true;
} else {
_isRecorded = false;
_isRecording = true;
await _startRecording();
}
setState(() {});
}
void _onPlayButtonPressed() {
if (!_isPlaying) {
_isPlaying = true;
_audioPlayer.play(_filePath, isLocal: true);
_audioPlayer.onPlayerCompletion.listen((duration) {
setState(() {
_isPlaying = false;
});
});
} else {
_audioPlayer.pause();
_isPlaying = false;
}
setState(() {});
}
Future<void> _startRecording() async {
final bool? hasRecordingPermission =
await FlutterAudioRecorder2.hasPermissions;
if (hasRecordingPermission ?? false) {
Directory directory = await getApplicationDocumentsDirectory();
String filepath = directory.path +
'/' +
DateTime.now().millisecondsSinceEpoch.toString() +
'.aac';
_audioRecorder =
FlutterAudioRecorder2(filepath, audioFormat: AudioFormat.AAC);
await _audioRecorder.initialized;
_audioRecorder.start();
_filePath = filepath;
setState(() {});
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Center(child: Text('Please enable recording permission'))));
}
}
}
Those 2 pages, how convert to like as a popup?
My voice recording functions work perfectly I'm asking to convert those two material pages to like popup windows.
You can use this package for recording the voice :
dependencies:
flutter_sound: ^9.2.13

How to make flutter google map prompt "Allow all the time" when asking permission the first time?

When google maps loads, location permission only asks to "Allow only while using the app". I want it to ask permission to allow all the time so that the location can be queried in the background by workmanger. How do I make it prompt as "Allow all the time"? Full code here. Thanks for reading. This should be pretty easy to figure out, sometimes I can get it to work on another github example here but somehow it breaks after I make changes.
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart' as loco;
import 'package:ungshowlocation/models/marker_collect_model.dart';
import 'package:ungshowlocation/widget/add_location.dart';
import 'package:ungshowlocation/widget/detail_marker.dart';
import 'package:ungshowlocation/widget/my_service.dart';
class ShowMap extends StatefulWidget {
final double lat;
final double lng;
ShowMap({Key key, this.lat, this.lng}) : super(key: key);
#override
_ShowMapState createState() => _ShowMapState();
}
class _ShowMapState extends State<ShowMap> {
// Field
double lat, lng;
BitmapDescriptor policeIcon;
List<Marker> list = List();
List<String> listDocuments = List();
final Set<Polyline> _polyline = {};
GoogleMapController controller;
List<LatLng> latlngSegment1 = List();
List<LatLng> latlngSegment2 = List();
static LatLng _lat1 = LatLng(45.19, -121.59);
static LatLng _lat2 = LatLng(45.30, -122.20);
static LatLng _lat3 = LatLng(45.11, -122.61);
static LatLng _lat4 = LatLng(45.42, -122.62);
static LatLng _lat5 = LatLng(45.34, -122.32);
static LatLng _lat6 = LatLng(45.21, -122.2);
bool _myLocationButtonEnabled = true;
bool _myLocationEnabled = true;
// Method
#override
void initState() {
super.initState();
// findLatLng();
readDataFromFirebase();
setState(() {
lat = widget.lat;
lng = widget.lng;
latlngSegment1.add(_lat1);
latlngSegment1.add(_lat2);
latlngSegment1.add(_lat3);
latlngSegment1.add(_lat4);
//line segment 2
latlngSegment2.add(_lat4);
latlngSegment2.add(_lat5);
latlngSegment2.add(_lat6);
latlngSegment2.add(_lat1);
});
}
Future<Null> readDataFromFirebase() async {
print('###############readDataFromFirebase Work####################');
Firestore firestore = Firestore.instance;
CollectionReference collectionReference =
firestore.collection('usertest');
await collectionReference.snapshots().listen((event) {
List<DocumentSnapshot> snapshots = event.documents;
for (var map in snapshots) {
MarkerCollectModel model = MarkerCollectModel.fromMap(map.data);
String nameDocument = map.documentID;
listDocuments.add(nameDocument);
print('Name ==>> ${model.name}');
Marker marker = createMarker(model, nameDocument);
setState(() {
list.add(marker);
print('myMarkers set lenght ==>> ${myMarkers().length}');
});
}
});
}
Marker createMarker(MarkerCollectModel markerCollectModel, String nameDocument) {
Marker marker;
Random random = Random();
int i = random.nextInt(100);
String idString = 'id$i';
marker = Marker(
markerId: MarkerId(idString),
position: LatLng(markerCollectModel.lat, markerCollectModel.lng),
infoWindow: InfoWindow(
title: markerCollectModel.name, snippet: markerCollectModel.detail),
onTap: () {
print('You Tab Name ==>> ${markerCollectModel.name}');
MaterialPageRoute route = MaterialPageRoute(
builder: (context) => DetailMarker(
model: markerCollectModel,nameDocument: nameDocument,
),
);
Navigator.push(context, route);
},
);
return marker;
}
Future<void> findLatLng() async {
loco.LocationData locationData = await findLocation();
setState(() {
lat = locationData.latitude;
lng = locationData.longitude;
print('lat =>>> $lat, lng ===>> $lng');
});
}
Future<loco.LocationData> findLocation() async {
var location = loco.Location();
try {
return await location.getLocation();
} catch (e) {
print('e location = ${e.toString()}');
return null;
}
}
Set<Marker> myMarkers() {
list.add(localMarker());
return list.toSet();
}
Marker localMarker() {
return Marker(
infoWindow: InfoWindow(
),
markerId: MarkerId('myLocotion'),
);
}
Widget showMap() {
print('latlng on showmap ===>>> $lat, $lng');
LatLng centerLatLng = LatLng(lat, lng);
CameraPosition cameraPosition =
CameraPosition(target: centerLatLng, zoom: 16.0);
return Stack(
children: <Widget>[
GoogleMap(
initialCameraPosition: cameraPosition,
mapType: MapType.normal,
markers: myMarkers(),
polylines: _polyline,
myLocationEnabled: _myLocationEnabled,
myLocationButtonEnabled: _myLocationButtonEnabled,
onMapCreated: _onMapCreated,
),
// addButton(),
],
);
}
Widget addButton() {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Container(
margin: EdgeInsets.only(
right: 40.0,
bottom: 40.0,
),
child: FloatingActionButton(
onPressed: () {
MaterialPageRoute route = MaterialPageRoute(
builder: (value) => MyService(
currentWidget: PageWidget(
),
));
Navigator.of(context)
.pushAndRemoveUntil(route, (value) => false);
},
child: Icon(
Icons.add_circle,
size: 36.0,
),
),
),
],
),
],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: lat == null
? Center(
child: CircularProgressIndicator(),
)
: showMap(),
);
}
void _onMapCreated(GoogleMapController controllerParam) {
setState(() {
controller = controllerParam;
_polyline.add(Polyline(
polylineId: PolylineId('line1'),
visible: true,
//latlng is List<LatLng>
points: latlngSegment1,
width: 2,
color: Colors.blue,
));
//different sections of polyline can have different colors
_polyline.add(Polyline(
polylineId: PolylineId('line2'),
visible: true,
//latlng is List<LatLng>
points: latlngSegment2,
width: 2,
color: Colors.red,
));
});
}
}

Return Text with current position Flutter

I want to return some Strings or Texts with :
name of the city
postal code
country
So this is my code :
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';
class Maps extends StatefulWidget {
static Future<void> show(
BuildContext context,
) async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Maps(),
fullscreenDialog: true,
),
);
}
#override
_MapsState createState() => _MapsState();
}
Future<Position> locateUser() async {
return Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
}
class _MapsState extends State<Maps> {
Geolocator geolocator = Geolocator();
Position _currentPosition;
String _location;
String _addressLine;
bool done = false;
#override
Widget build(BuildContext context) {
_getCurrentLocation();
_getLocation(_currentPosition);
return Scaffold(
body: Center(
child: Container(
height: MediaQuery.of(context).size.height * 0.4,
width: MediaQuery.of(context).size.width * 0.6,
child: Center(
child: Column(
children: [
done == false
? Text("Need to get the position")
: Text("val 1: $_location, val 2: $_addressLine"),
FlatButton(
child: Text("Get location"),
onPressed: () {
_getCurrentLocation();
},
),
],
),
),
),
),
);
}
Future<void> _getLocation(Position position) async {
debugPrint('location: ${position.latitude}');
final coordinates = new Coordinates(position.latitude, position.longitude);
List<Address> addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
Address first = addresses.first;
_location = "${first.featureName}";
_addressLine = " ${first.addressLine}";
done = true;
}
void _getCurrentLocation() {
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
}).catchError((e) {
print(e);
});
}
}
The problem is that it's always returned "Need to get the position" instead of real address.
I know this code isn't the best but it's what comes from hours of researches, I didn't find some clear explanations about the use of geo functions.
I only just made few changes to your code, as i dont want to ruin your code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';
class Maps extends StatefulWidget {
static Future<void> show(
BuildContext context,
) async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Maps(),
fullscreenDialog: true,
),
);
}
#override
_MapsState createState() => _MapsState();
}
Future<Position> locateUser() async {
return Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
}
class _MapsState extends State<Maps> {
Geolocator geolocator = Geolocator();
Position _currentPosition;
String _location;
String _addressLine;
bool done = false;
#override
void initState() {
_getCurrentLocation();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: MediaQuery.of(context).size.height * 0.4,
width: MediaQuery.of(context).size.width * 0.6,
child: Center(
child: Column(
children: [
done == false
? Text("Need to get the position")
: Text("val 1: $_location, val 2: $_addressLine"),
FlatButton(
child: Text("Get location"),
onPressed: () {
_getCurrentLocation();
},
),
],
),
),
),
),
);
}
Future<void> _getLocation(Position position) async {
debugPrint('location: ${position.latitude}');
final coordinates = new Coordinates(position.latitude, position.longitude);
List<Address> addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
Address first = addresses.first;
_location = "${first.featureName}";
_addressLine = " ${first.addressLine}";
setState(() {
done = true;
});
}
void _getCurrentLocation() {
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
_getLocation(position);
}).catchError((e) {
print(e);
});
}
}