file downloader app with package sn progress dialog - flutter

How to change the progress_dialog package to the sn_progress_dialog package? I'm trying to make a file downloader app with a progress dialog, but the progress_dialog package is not null safety.
Future _downloadAndSaveFileToStorage(String urlPath) async {
final name = urlPdf.split('/').last;
ProgressDialog pr;
pr = ProgressDialog(context, type: ProgressDialogType.Normal);
pr.style(message: "Download file ...");
try{
await pr.show();
final Directory _documentDir = Directory('/storage/emulated/0/MyDocuments/$name');
await dio!.download(urlPath, _documentDir.path, onReceiveProgress: (rec, total){
setState(() {
_isLoading = true;
progress = ((rec / total)*100).toStringAsFixed(0) + " %";
print(progress);
pr.update(message: "Please wait : $progress");
});
});
pr.hide();
_fileFullPath = _documentDir.path;
} catch (e) {
print(e);
}
setState(() {
_isLoading = false;
});
}
And this is my screenshot app with progress_dialog package.

Just do like this :
Future _downloadAndSaveFileToStorage(String urlPath) async {
final name = urlPdf.split('/').last;
ProgressDialog pd = ProgressDialog(context: context);
try{
pd.show(max: 100, msg: 'Download file ...');
final Directory _documentDir = Directory('/storage/emulated/0/MyDocuments/$name');
await dio!.download(urlPath, _documentDir.path, onReceiveProgress: (rec, total){
setState(() {
_isLoading = true;
progress = ((rec / total)*100).toStringAsFixed(0) + " %";
print(progress);
pd.update(progress);
});
});
pd.close();
_fileFullPath = _documentDir.path;
} catch (e) {
pd.close();
print(e);
}
setState(() {
_isLoading = false;
});
}
and you can change color or message in show method like this :
pd.show(
max: 100,
msg: 'Preparing Download...',
progressType: ProgressType.valuable,
backgroundColor: Color(0xff212121),
progressValueColor: Color(0xff3550B4),
progressBgColor: Colors.white70,
msgColor: Colors.white,
valueColor: Colors.white);

just need a little tweaking :
Future _downloadAndSaveFileToStorage(String urlPath) async {
final name = urlPdf.split('/').last;
ProgressDialog pd = ProgressDialog(context: context);
try{
pd.show(
max: 100,
msg: 'Preparing Download...',
progressType: ProgressType.valuable,
backgroundColor: Color(0xff212121),
progressValueColor: Color(0xff3550B4),
progressBgColor: Colors.white70,
msgColor: Colors.white,
valueColor: Colors.white
);
final Directory _documentDir = Directory('/storage/emulated/0/MYDocuments/$name');
await dio!.download(urlPath, _documentDir.path, onReceiveProgress: (rec, total){
setState(() {
_isLoading = true;
int progress = (((rec / total) * 100).toInt());
print(progress);
pd.update(value: progress, msg: 'File Downloading');
});
});
pd.close();
_fileFullPath = _documentDir.path;
} catch (e) {
pd.close();
print(e);
}
setState(() {
_isLoading = false;
});
}

Related

flutter google_speach response stream not working

final serviceAccount = ServiceAccount.fromString(r'''{
Json private keys
}''');
final speechToText = SpeechToText.viaServiceAccount(serviceAccount);
final config = RecognitionConfig(
encoding: AudioEncoding.LINEAR16,
model: RecognitionModel.basic,
enableAutomaticPunctuation: true,
sampleRateHertz: 16000,
languageCode: 'en-US');
final streamingConfig =
StreamingRecognitionConfig(config: config, interimResults: true);
Stream<List<int>> stream =
(await MicStream.microphone(sampleRate: 16000)) as Stream<List<int>>;
final responseStream =
speechToText.streamingRecognize(streamingConfig, stream);
if (_isListining) {
setState(() {
_isListining = false;
});
} else {
setState(() {
_isListining = true;
print('hello');
try {
responseStream.listen((data) {
print(data.results.length);
setState(() {
_sendController.text = data.results
.map((e) => e.alternatives.first.transcript)
.join('/n');
});
print(content);
}, onDone: () {
setState(() {
setState(() {
_isListining = false;
});
});
}, onError: (e) {
print('errorr : ' + e);
setState(() {
_isListining = false;
});
});
print('streaming');
} catch (e) {
print('not streaming');
print(e);
}
});
}
linke to packages used
https://pub.dev/packages/google_speech
https://pub.dev/packages/mic_stream
so the problem is that microphone streaming is working fine but responseStream from google apis not printing or doing anything
after reading the docs
found this
https://cloud.google.com/speech-to-text/docs/troubleshooting#returns_an_empty_response
and i dont know if it is the problem or not

Flutter- Android - App crash When Using faceDetector on imageStream

whenever I use the app with face detector in debug, profile, or release mode it works fine but when i build the app and install it then start it the app automatically close after the camera stream starts
im using google_ml_kit: ^0.7.3 and camera: ^0.9.4+14
this is the code i use to initialize the camera and start detecting every time
void initCamera() async {
final description = await availableCameras().then(
(cameras) => cameras.firstWhere(
(camera) => camera.lensDirection == CameraLensDirection.front,
),
);
cameraControllerNotifier.value = CameraController(
description,
ResolutionPreset.low,
enableAudio: false,
);
await cameraControllerNotifier.value!.initialize();
await Future.delayed(const Duration(milliseconds: 500));
isDetecting = false;
cameraControllerNotifier.value!.startImageStream((img) async {
if (isDetecting) return;
if (cameraControllerNotifier.value != null) {
isDetecting = true;
final image = InputImage.fromBytes(
bytes: img.planes[0].bytes,
inputImageData: InputImageData(
inputImageFormat:
InputImageFormatMethods.fromRawValue(img.format.raw)!,
size: Size(img.width.toDouble(), img.height.toDouble()),
imageRotation: MlHelper.rotationIntToImageRotation(
description.sensorOrientation,
),
planeData: null,
),
);
try {
final faceDetector = GoogleMlKit.vision.faceDetector(
const FaceDetectorOptions(
mode: FaceDetectorMode.accurate,
enableLandmarks: true,
),
);
List<Face> _faces = await faceDetector.processImage(image);
if (_faces.isNotEmpty) {
//..........
} else {
isClose.value = false;
}
isDetecting = false;
// facesNotifier.value = _faces;
} catch (e) {
isClose.value = false;
isDetecting = false;
log("FaceKIt Error : $e");
}
}
});
if (mounted) {
setState(() {});
}
}

How to call button tap functionality outside of button in Flutter

I want to call the onTap functionality outside of my button. As soon as I receive my OTP, I want to call the onTap of my manually created widget. I have a custom widget called as LoginCTA and I want to call it's onTap after I receive my OTP in initSmsListener method which I called in initState.
My code -
String _comingSms = 'Unknown';
Future<void> initSmsListener() async {
String comingSms;
try {
comingSms = await AltSmsAutofill().listenForSms??"";
} on PlatformException {
comingSms = 'Failed to get Sms.';
}
if(!mounted)
return;
setState(() {
_comingSms=comingSms;
print("\n \n \n Coming SMS - $_comingSms");
otpController.text = _comingSms[23] + _comingSms[24] + _comingSms[25] + _comingSms[26]
+ _comingSms[27] + _comingSms[28];
});
//Apply here -
}
#override
void initState() {
initSmsListener();
super.initState();
}
isOTP
? LoginCTA(
//After input otp
onPressed: () async {
print(Provider.of<APIData>(context, listen: false)
.loggedIN);
if (emailEntered &&
otpController.text.length == 6) {
bool res;
try {
res = await widget.signInWithOTP(
contactController.text, otpController.text);
} catch (e) {
res = false;
print(e);
}
if (res) {
Fluttertoast.showToast(
msg: "Verifying OTP...",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
textColor: cardColor,
backgroundColor: primaryTextColor,
fontSize: 16.0,
);
Timer(Duration(seconds: 2), () {
print(Provider.of<APIData>(context,
listen: false)
.loggedIN);
if (Provider.of<APIData>(context,
listen: false)
.loggedIN ==
1) {
Navigator.pop(context);
}
});
}
}
},
btnText: otpButtonText,
isDisabled: isDisabled,
)
: LoginCTA(
//After input mobile number
onPressed: () async {
if (emailEntered &&
contactController.text.length == 10) {
widget.sendOTP(contactController.text);
setState(() {
isOTP = true;
isDisabled = true;
});
} else {
print('kuch na kuch glti');
}
},
btnText: buttonText,
isDisabled: isDisabled,
hasIcon: hasIcon,
),
Just extract the functionality out into its own function. Then you can assign the function to onTap and also call it whenever you like.

Display Loading spinner waitint for request to complete while using provider package

I am using a provider package. I want to display a loading spinner while waiting for a request to complete. The pattern below is too verbose. Please help me make it less verbose. Here is my code
class APIService with ChangeNotifier {
// Check for working API backend
bool isWorking = false;
bool isLoading = false;
set _isLoading(bool value) {
isLoading = value; <--
notifyListeners();
}
Future<bool> selectAPI(String input) async {
_isLoading = true; <-- 1
final uri = Uri.tryParse('https://$input$url')!;
final response = await http.get(uri);
if (response.statusCode == 200) {
final body = jsonDecode(response.body) as Map<String, dynamic>;
bool isTrue = body['info']['title'] == 'SamFetch';
_isLoading = false; <-- 2
notifyListeners();
return isWorking = isTrue;
}
_isLoading = false; <-- 3
throw response;
}
}
Here is my UI code
IconButton(
icon: apiService.isLoading
? CircularProgressIndicator()
: Icon(Icons.done),
onPressed: () async {
await addAPI(apiService, cache);
}),
}
Below is addAPI() method
Future<void> addAPI(APIService apiService, Cache cache) async {
if (api != null) {
try {
await apiService.selectAPI(api!);
if (apiService.isWorking) {
await cache.saveAppName(api!);
}
} on SocketException catch (e) {
print(e);
} catch (e) {
await cache.clearCache();
}
}
}
Is setState the final solution?
You can use Future Builder and set your Future Function in future attribute. You can control the visible widget based on the status of your function. So you dont have to use isloading variable.

Flutter file_picker package giving null value for all file details

I've copied the same code from file_picker package docs, but it keeps giving me a null value for all file details, here is the code I've copied
FilePickerResult result = await FilePicker.platform.pickFiles();
if(result != null) {
PlatformFile file = result.files.first;
print(file.name);
print(file.bytes);
print(file.size);
print(file.extension);
print(file.path);
}
The file name, bytes, size, extension and path are all giving a null value. Anyone know what is the reason for that ?
I've tried to upload a pdf, png, jpg, doc and get the same null value for all of them.
I'm using the latest version of this:
https://pub.dev/packages/file_picker
void _openFileExplorer() async {
File _pickedFile;
FilePickerResult _filePickerResult;
setState(() {
_isLoading = true;
});
try {
_filePickerResult = await FilePicker.platform.pickFiles(
type: FileType.any,
allowedExtensions: (_extension?.isNotEmpty ?? false)
? _extension?.replaceAll(' ', '')?.split(',')
: null);
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (_filePickerResult != null) {
setState(() {
_pickedFile = File(_filePickerResult.files.single.path);
});
}
if (!mounted) return;
{
Flushbar(
showProgressIndicator: true,
progressIndicatorBackgroundColor: Colors.blueGrey,
title: 'Status:',
message: 'File loaded: $_pickedFile',
duration: Duration(seconds: 3),
backgroundColor: Colors.green,
)
..show(context);
}
setState(() {
_isLoading = false;
});
}