How convert material page as a dialog box on flutter? - 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'))));
}
}
}

Related

loadingbar not working using getx 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 ?

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 automatically trigger record

I have a audio recording page which starts when I tap in the button and stop when i tap the button once again
import 'package:flutter_sound/flutter_sound.dart';
import 'package:permission_handler/permission_handler.dart';
class AudioWidget extends StatefulWidget {
#override
State<AudioWidget> createState() => _AudioWidgetState();
}
``class _AudioWidgetState extends State<AudioWidget> {
final FirebaseAuth _auth = FirebaseAuth.instance;
String AudioUrl = '';
final recorder = FlutterSoundRecorder();
bool isRecorderReady = false;
#override
void initState() {
super.initState();
initRecorder();
record();
}
#override
void dispose() {
recorder.closeRecorder();
super.dispose();
}
Future initRecorder() async {
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
throw 'Microphone permission not granted';
}
await recorder.openRecorder();
isRecorderReady = true;
recorder.setSubscriptionDuration(const Duration(milliseconds: 500));
}
Future record() async {
if (!isRecorderReady) {
return;
}
await recorder.startRecorder(toFile: 'audio');
}
Future stop() async {
if (!isRecorderReady) {
return;
}
final path = await recorder.stopRecorder();
final audioFile = File(path!);
print('Recorder audio: $audioFile');
final ref = FirebaseStorage.instance
.ref()
.child('Audio')
.child(DateTime.now().toIso8601String() + ".mp3");
await ref.putData(audioFile.readAsBytesSync());
AudioUrl = await ref.getDownloadURL();
FirebaseFirestore.instance.collection('Audio').add({
'AudioUrl': AudioUrl,
'userId': _auth.currentUser!.email,
'createdAt': DateTime.now(),
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Audio"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamBuilder<RecordingDisposition>(
stream: recorder.onProgress,
builder: (context, snapshot) {
final duration = snapshot.hasData
? snapshot.data!.duration
: Duration.zero;
String twoDigits(int n) => n.toString().padLeft(2, '0');
final twoDigitMinutes =
twoDigits(duration.inMinutes.remainder(60));
final twoDigitSeconds =
twoDigits(duration.inSeconds.remainder(60));
if (twoDigitSeconds ==
FFAppState().AudioMaxDuration.toString()) {
stop();
}
return Text('$twoDigitMinutes:$twoDigitSeconds',
style: const TextStyle(
fontSize: 80,
fontWeight: FontWeight.bold,
));
}),
const SizedBox(height: 32),
ElevatedButton(
child: Icon(
recorder.isRecording ? Icons.stop : Icons.mic,
size: 80,
),
onPressed: () async {
if (recorder.isRecording) {
await stop();
context.pop();
} else {
await record();
}
setState(() {});
},
),
],
)),
),
);
}
}
how can I automatically start recording once I open the audio recording page and tap it to stop and tap again to start?
I tried to put the record function in initstate but it didn't work
void initState() {
super.initState();
initRecorder();
record();
}

Flutter Camera recorded Video are incompatible with browsers - how to convert to .mp4?

I'm trying to capture a video and upload it to firebase storage.
The problem is, the recorded video format is .mov and this format seems to be incompatible with browsers.
How could I convert the recorded file to .mp4?
Below is the code I use to record and upload my videos.
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
class CameraTestPage extends StatefulWidget {
const CameraTestPage({Key? key}) : super(key: key);
#override
_CameraTestPageState createState() => _CameraTestPageState();
}
class _CameraTestPageState extends State<CameraTestPage> {
List<CameraDescription>? cameras;
CameraController? controller;
bool frontCamera = false;
XFile? videoFile;
VideoPlayerController? videoController;
VoidCallback? videoPlayerListener;
#override
void initState() {
initCamera();
super.initState();
}
initCamera() async {
if (cameras == null) {
cameras = await availableCameras();
}
if (controller?.value.isInitialized ?? false) {
controller!.dispose();
}
controller = CameraController(
cameras!.firstWhere(
(element) => element.lensDirection == (frontCamera ? CameraLensDirection.front : CameraLensDirection.back),
),
ResolutionPreset.medium,
enableAudio: false,
);
controller!.initialize().then((value) {
setState(() {});
});
}
void onVideoRecordButtonPressed() {
startVideoRecording().then((_) {
if (mounted) setState(() {});
});
}
void onStopButtonPressed() {
stopVideoRecording().then((file) {
if (mounted) setState(() {});
if (file != null) {
print('Video recorded to ${file.path}');
videoFile = file;
_startVideoPlayer();
}
});
}
Future<void> _startVideoPlayer() async {
if (videoFile == null) {
return;
}
final VideoPlayerController vController = VideoPlayerController.file(File(videoFile!.path));
videoPlayerListener = () {
if (videoController != null && videoController!.value.size != null) {
// Refreshing the state to update video player with the correct ratio.
if (mounted) setState(() {});
videoController!.removeListener(videoPlayerListener!);
}
};
vController.addListener(videoPlayerListener!);
await vController.setLooping(true);
await vController.initialize();
await videoController?.dispose();
if (mounted) {
setState(() {
videoController = vController;
});
}
await vController.play();
}
Future<void> startVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isInitialized) {
print('Error: select a camera first.');
return;
}
if (cameraController.value.isRecordingVideo) {
// A recording is already started, do nothing.
return;
}
try {
await cameraController.startVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return;
}
}
Future<XFile?> stopVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isRecordingVideo) {
return null;
}
try {
return cameraController.stopVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
}
void _showCameraException(CameraException e) {
print('Error: ${e.code}\n${e.description}');
}
_uploadVideo() async {
Reference ref = FirebaseStorage.instance.ref("test/test.mov");
UploadTask uploadTask = ref.putFile(File(videoFile!.path), SettableMetadata(contentType: 'video/mov'));
print("uploading");
uploadTask.whenComplete(() async {
String downloadUrl = await ref.getDownloadURL();
print("download url: $downloadUrl");
});
}
Widget _thumbnailWidget() {
final VideoPlayerController? localVideoController = videoController;
return Expanded(
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
child: (localVideoController == null)
? Center(
child: Container(
child: Text("none"),
),
)
: Container(
child: AspectRatio(
aspectRatio: localVideoController.value.aspectRatio,
child: VideoPlayer(localVideoController),
),
decoration: BoxDecoration(
border: Border.all(color: Colors.pink),
),
),
),
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Camera Test")),
body: Column(
children: [
if (controller != null)
Container(
child: CameraPreview(controller!),
height: 400,
),
Row(
children: [
ElevatedButton(
onPressed: () {
frontCamera = !frontCamera;
initCamera();
},
child: Text("Switch"),
),
ElevatedButton(
onPressed: () {
controller?.value.isRecordingVideo ?? false ? onStopButtonPressed() : onVideoRecordButtonPressed();
},
child: Text(controller?.value.isRecordingVideo ?? false ? "Stop" : "Record"),
),
ElevatedButton(
onPressed: videoFile != null ? _uploadVideo : null,
child: Text("Upload video"),
),
],
),
_thumbnailWidget(),
],
),
);
}
}
You can use the video_compress package to convert the video to mp4.
Here is your _uploadVideo() method updated to include this:
_uploadVideo() async {
Reference ref = FirebaseStorage.instance.ref("test/test.mp4");
MediaInfo? mediaInfo = await VideoCompress.compressVideo(
videoFile!.path,
quality: VideoQuality.DefaultQuality,
deleteOrigin: false, // It's false by default
);
UploadTask uploadTask = ref.putFile(
File(mediaInfo!.path!), SettableMetadata(contentType: 'video/mp4'));
print("uploading");
uploadTask.whenComplete(() async {
String downloadUrl = await ref.getDownloadURL();
print("download url: $downloadUrl");
});
}
Ensure you import the package by including this line:
import 'package:video_compress/video_compress.dart';

How to solve "NoSuchMethodError: The method 'findRenderObject' was called on null" error?

I'm trying to save a QR image and add sharing optionality for that, but while doing so I'm facing with this "findRenderObject was called on null" object.
How can I solve this error? This is the code below
GenerateQr.dart
import 'package:attendee/services/database.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'dart:ui';
import 'package:flutter/rendering.dart';
import 'package:intl/intl.dart';
import 'package:attendee/constants.dart';
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
class GeneratePage extends StatefulWidget {
#override
State<StatefulWidget> createState() => GeneratePageState();
}
class GeneratePageState extends State<GeneratePage> {
String qrData =
"https://github.com/neon97"; // already generated qr code when the page opens
FirebaseAuth auth = FirebaseAuth.instance;
String subject;
GlobalKey globalKey = new GlobalKey();
final CollectionReference student_details =
FirebaseFirestore.instance.collection('students');
final CollectionReference tutor_details =
FirebaseFirestore.instance.collection("tutors");
String timeString;
bool _validate = false;
// String formattedDate = DateFormat('kk:mm:ss \n EEE d MMM').format(now);
static const double _topSectionTopPadding = 50.0;
static const double _topSectionBottomPadding = 20.0;
static const double _topSectionHeight = 50.0;
void _getTime() {
final String formattedDateTime =
DateFormat('yyyy-MM-dd \n kk:mm:ss').format(DateTime.now()).toString();
//DateFormat('yyyy-MM-dd').toString();
setState(() {
timeString = formattedDateTime;
});
}
#override
void initState() {
super.initState();
Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());
}
#override
Widget build(BuildContext context) {
var numberOfClasses;
return Scaffold(
appBar: AppBar(
title: Text('QR Code Generator'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: _captureAndSharePng,
)
],
),
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
QrImage(
//plce where the QR Image will be shown
data: qrData,
),
SizedBox(
height: 40.0,
),
Text(
"New QR Link Generator",
style: TextStyle(fontSize: 20.0),
),
TextField(
controller: qrdataFeed,
decoration: InputDecoration(
hintText: "SUBJECT-anything",
errorText:
_validate ? "Please enter in Sub-Date format!" : null,
),
),
Padding(
padding: EdgeInsets.fromLTRB(40, 20, 40, 0),
child: MaterialButton(
minWidth: double.infinity,
height: 60,
onPressed: () async {
qrdataFeed.text
.contains(RegExp(r'^[a-zA-Z]*\-[a-zA-Z]*$'))
? _validate = false
: _validate = true;
if (qrdataFeed.text.isEmpty) {
//a little validation for the textfield
if (!mounted) return;
setState(() {
qrData = "";
});
} else {
int index = qrdataFeed.text.indexOf('-');
subject = qrdataFeed.text.substring(0, index);
print("Subject name is $subject");
String user = isTutor ? "tutors" : "students";
String uid = FirebaseAuth.instance.currentUser.uid;
numberOfClasses = await FirebaseFirestore.instance
.collection(user)
.doc(uid)
.get()
.then((value) {
return value.data()['numberOfClasses'];
});
String rollno = await FirebaseFirestore.instance
.collection(user)
.doc(uid)
.get()
.then((value) {
return value.data()['rollno'];
});
print('$numberOfClasses is printed pehle');
await DatabaseService().attendance(rollno);
setState(() {
qrData = qrdataFeed.text;
scanned = true;
print('done');
numberOfClasses += 1; //idhar se dekhke
print('$numberOfClasses is printed');
});
await tutor_details.doc(uid).set(
{'numberOfClasses': numberOfClasses},
SetOptions(merge: true));
}
},
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black,
),
borderRadius: BorderRadius.circular(50)),
child: Text(
"Generate QR",
style:
TextStyle(fontWeight: FontWeight.w600, fontSize: 18),
),
)),
],
),
),
),
);
}
final qrdataFeed = TextEditingController();
Future<void> _captureAndSharePng() async {
try {
RenderRepaintBoundary boundary =
globalKey.currentContext.findRenderObject();
print(boundary);
var image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final file = await new File('${tempDir.path}/image.png').create();
await file.writeAsBytes(pngBytes);
final channel = const MethodChannel('channel:me.attendee.share/share');
channel.invokeMethod('shareFile', 'image.png');
} catch (e) {
print(e.toString());
}
}
}
The error is here:
RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
Try changing globalKey.currentContext with context and see if the error is solved
Bye :D