Flutter: is Dialog on top of Navigator (stack)? - asynchronous

How do I determine whether some dialog is being displayed or top of the stack is a dialog?
I have an async function that pushes a dialog (Like post request with loading dialog). When the response comes, loading the dialog closed(pop) then message dialog is pushed.
But the problem is:
If I send multiple requests, sometimes the loading screen stays on top...

bool dialogIsVisible(BuildContext context) {
bool isVisible = false;
Navigator.popUntil(context, (route) {
isVisible = route is PopupRoute;
return !isVisible;
});
return isVisible;
}

You can check if a Dialog is on top of the Navigator object by doing a little verification:
void _verifyDialog(context) {
var _isDialogOnTop = false;
var stackCount = 0;
Navigator.popUntil(context, (route) {
if (!_isDialogOnTop && route.toString().contains("_DialogRoute")) {
_isDialogOnTop = true;
}
else{
stackCount++;
}
return _isDialogOnTop || stackCount > 0;
});
print (_isDialogOnTop);
}

Related

Switch camera on webview video call

I have app in xamarin form where i am accessing webview for video call. Everything is working fine just i need to know how i can switch back/front camera during call? as when video call start front camera open by default.
Code for initializing video call
function initializeLocalMedia(options, callback) {
if(options) {
options['audio'] = true;
if(options['video'])
options['video'] = true;
} else {
options['audio'] = true;
options['video'] = false;
}
// Get audio/video stream
navigator.getUserMedia(options, function(stream) {
// Set your video displays
window.localStream = stream;
myapp.setMyVideo(window.localStream)
if(callback)
callback();
}, function(err) {
console.log("The following error occurred: " + err.name);
alert('Unable to call ' + err.name)
});
}
Going straight to code then it should look like:
Camera.CameraInfo camInfo = new Camera.CameraInfo ();
for (int i = 0; i < Camera.NumberOfCameras; i++) {
Camera.GetCameraInfo (i, camInfo);
if (camInfo.Facing == CameraFacing.Front){
try {
return Camera.Open(i);
} catch (Exception e) {
// log or something
}
}
}
return null;
What we are doing is iterating over the hardware and then check to match the front camera, if it match then do the things. Same is true for back camera too

Flutter async method slowdown app performance

I'm a newbie in flutter and I can't understand what I might be doing wrong. In my App there is an option for the user to change their avatar's image. He can choose an image from the gallery or take a photo. The new avatar image is saved in the _avatarImage field, and within the setState method the _newImage field is set to true, like this:
Future getNewAvatarImage() async {
Image _image = .... // Take a photo or a image from Gallery
// ...
_avatarImage = _image;
setState(
() => _newImage = true;
);
}
In one part of the code I have the compressAndUpload method which when called compresses an image and sends it to the remote server. This method is asynchronous and is called within the build method whenever the _newImage field is true. Like this
#override
Widget build(BuildContext context) {
if (_newImage) {
_newImage = false;
compressAndUpload(_avatarImage);
}
return Container(
//...
child: _avatarImage,
//
);
The problem is that the new avatar image will take a long time to appear if the compressAndUpload method is called. If this method is commented out the new avatar image comes up quickly.
if (_newImage) {
_newImage = false;
// New image show quickly
// compressAndUpload(_avatarImage);
}
***********
if (_newImage) {
_newImage = false;
// Image takes too long to appear
compressAndUpload(_avatarImage);
}
Where is the problem? The compressAndUpload method is asynchronous and so should not cause delay for the new image to be displayed:
Future<void> compressAndUpload(var image) async {
// Compress image
// upload image
}
UPDATE:
For further clarification I show the complete code of the compressAndUpload method:
Future<void> compressAndUpload(var image) async {
var imageBytes = imagem.readAsBytesSync();
saveImageToPreferences(base64String(imageBytes));
var tempDir = await getTemporaryDirectory();
var path = tempDir.path;
// Reduce size
img.Image image = img.decodeImage(imageBytes);
img.Image smallerImage = img.copyResize(image, width: 1000);
File compressedFileImage =
File('$path\${Explika.getAluno().id}.jpg')
..writeAsBytesSync(img.encodeJpg(smallerImage, quality: 50));
String _urlsegment = Explika.producaoFlag ?
'https://www.remoteserver.pt' : 'http://10.0.2.2';
var stream = http.ByteStream(DelegatingStream.typed(
compressedFileImage.openRead()));
var length = await compressedFileImage.length();
var uri = Uri.parse('$_urlsegment/explika/api/upload');
var request = http.MultipartRequest("POST", uri);
var multipartFile = http.MultipartFile('fotoaluno', stream, length,
filename: '${Explika.getAluno().id}.jpg');
request.files.add(multipartFile);
var response;
try {
response = await request.send();
} catch (e) {
// mostrar falha de rede
//_uploadingImagem = false;
print(e);
return;
}
//Get the response from the server
var responseData = await response.stream.toBytes();
var responseString = String.fromCharCodes(responseData);
print(responseString);
}
Thanks so much for all the comments.
The problem was solved when I found that in the pickImage method it was possible to set the maximum width and the maximum height of the image being selected. Thus, the compression step of the selected image was not required.

Xamarin forms: Selected picture is not showing in UI from gallery and camera for IOS

Complete Scenario
I have an add icon on one page, it will show camera and gallery options when tap. If choose the camera, I will open another content page and open camera there. But the captured picture is not showing in the UI. Same for the gallery, selected image from the gallery is not showing in UI. This feature is working fine in android and not working in IOS.
Codes
When click add icon
string action = await DisplayActionSheet(null, "Cancel", null, "Camera", "Gallery");
if (action == "Camera")
{
await Navigation.PushModalAsync(new NewTweetPage("Camera"));
}
else if (action == "Gallery")
{
await Navigation.PushModalAsync(new NewTweetPage("Gallery"));
}
When entering next page
public NewTweetPage(String medium)
{
InitializeComponent();
if (medium == "Camera" )
{
OpenMyCamera();
}
else if(medium == "Gallery")
{
OpenMygallery();
}
}
public async void OpenMyCamera()
{
try
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Camera", "No camera available.", "OK");
return;
}
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
AllowCropping = true
});
if (_mediaFile == null)
return;
tweetPicture.Source = ImageSource.FromStream(() =>
{
isPicture = true;
return _mediaFile.GetStream();
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
}
public async void OpenMygallery()
{
try
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Gallery", ":( No photos available.", "OK");
return;
}
_mediaFile = await CrossMedia.Current.PickPhotoAsync();
if (_mediaFile == null)
return;
tweetPicture.Source = ImageSource.FromStream(() =>
{
isPicture = true;
return _mediaFile.GetStream();
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
}
The same code is working fine in profile page part, but in that case, there is no page navigation, everything is happening on the same page.
Don't know what is the problem with the current code, please help me to solve this issue.
Putting navigation commands in the constructor can cause issues. I would recommend putting them in the OnAppearing override. Also, instead of having a try...catch around a large section of code, you should handle null-checks or similar in code.

Older asynchronous messages overwriting newer ones

We are developing a document collaboration tool in SignalR where multiple users can update one single WYSIWYG form.
We are struggling getting the app to work using the KeyUp method to send the changes back to the server. This causes the system to overwrite what the user wrote after his first key stroke when it sends the message back.
Is there anyway to work around this problem?
For the moment I tried to set up a 2 seconds timeout but this delays all updates not only the "writer" page.
public class ChatHub : Hub
{
public ChatHub()
{
}
public void Send(int id,string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(id,message); //id is for the document id where to update the content
}
}
and the client:
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//console.log("Declare a proxy to reference the hub.");
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (id, message) {
var encodedValue = $('<div />').text(id).html();
// Add the message to the page.
if (encodedValue == $('#hdnDocId').val()) {
$('#DiaplayMsg').text(message);
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message); //!!!
}
};
// Start the connection.
$.connection.hub.start().done(function (e) {
//console.log("Start the connection.");
if ($('#hdnDocId').val() != '') {
tinyMCE.activeEditor.onKeyUp.add(function (ed, e) {
var elelist = $(tinyMCE.activeEditor.getBody()).text();
var content = tinyMCE.get('txtContent').getContent();
function Chat() {
var content = tinyMCE.get('txtContent').getContent();
chat.server.send($('#hdnDocId').val(), content); //send a push to server
}
typewatch(Chat, 2000);
});
}
});
});
var typewatch = function () {
var timer = 0;
return function (Chat, ms) {
clearTimeout(timer);
timer = setTimeout(Chat, ms);
}
} ();
</script>
Hello, here is an update of the client KeyUp code. It seems to be working but I would like your opinion. I've used a global variable to store the timeout, see below:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//console.log("Declare a proxy to reference the hub.");
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (id, message) {
var encodedValue = $('<div />').text(id).html();
var currenttime = new Date().getTime() / 1000 - 2
if (typeof window.istyping == 'undefined') {
window.istyping = 0;
}
if (encodedValue == $('#hdnDocId').val() && window.istyping == 0 && window.istyping < currenttime) {
function Update() {
$('#DiaplayMsg').text(message);
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message); //!!!
// tinyMCE.get('txtContent').setContent(message);
window.istyping = 0
}
Update();
}
};
// Start the connection.
$.connection.hub.start().done(function (e) {
//console.log("Start the connection.");
if ($('#hdnDocId').val() != '') {
tinyMCE.activeEditor.onKeyUp.add(function (ed, e) {
var elelist = $(tinyMCE.activeEditor.getBody()).text();
var content = tinyMCE.get('txtContent').getContent();
function Chat() {
//alert("Call");
var content = tinyMCE.get('txtContent').getContent();
chat.server.send($('#hdnDocId').val(), content);
window.istyping = new Date().getTime() / 1000;
}
Chat();
});
}
});
});
var typewatch = function () {
var timer = 0;
return function (Chat, ms) {
clearTimeout(timer);
timer = setTimeout(Chat, ms);
}
} ();
Thanks,
Roberto.
Is there anyway to work around this problem?
Yes, by not sending the entire document to the server, but document elements like paragraphs, table cells, and so on. You can synchronize these after the user has stopped typing for a period, or when focus is lost for example.
Otherwise add some incrementing counter to the messages, so older return values don't overwrite newer ones arriving earlier.
But you're basically asking us to solve a non-trivial problem regarding collaborated document editing. What have you tried?
"This causes the system to overwrite what the user wrote"
that's because this code isn't making any effort to merge changes. it is just blindly overwriting whatever is there.
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message);
as #CodeCaster hinted, you need to be more precise in the messages you send - pass specific changes back and forth rather re-sending the entire document - so that changes can be carefully merged on the receiving side

Close/kill the session when the browser or tab is closed

Can somebody tell me how can I close/kill the session when the user closes the browser? I am using stateserver mode for my asp.net web app. The onbeforeunload method is not proper as it fires when user refreshes the page.
You can't. HTTP is a stateless protocol, so you can't tell when a user has closed their browser or they are simply sitting there with an open browser window doing nothing.
That's why sessions have a timeout - you can try and reduce the timeout in order to close inactive sessions faster, but this may cause legitimate users to have their session timeout early.
As said, the browser doesn't let the server know when it closes.
Still, there are some ways to achieve close to this behavior. You can put a small AJAX script in place that updates the server regularly that the browser is open. You should pair this with something that fires on actions made by the user, so you can time out an idle session as well as one that has closed out.
As you said the event window.onbeforeunload fires when the users clicks on a link or refreshes the page, so it would not a good even to end a session.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx describes all situations where window.onbeforeonload is triggered. (IE)
However, you can place a JavaScript global variable on your pages to identify actions that should not trigger a logoff (by using an AJAX call from onbeforeonload, for example).
The script below relies on JQuery
/*
* autoLogoff.js
*
* Every valid navigation (form submit, click on links) should
* set this variable to true.
*
* If it is left to false the page will try to invalidate the
* session via an AJAX call
*/
var validNavigation = false;
/*
* Invokes the servlet /endSession to invalidate the session.
* No HTML output is returned
*/
function endSession() {
$.get("<whatever url will end your session>");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
This script may be included in all pages
<script type="text/javascript" src="js/autoLogoff.js"></script>
Let's go through this code:
var validNavigation = false;
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
A global variable is defined at page level. If this variable is not set to true then the event windows.onbeforeonload will terminate the session.
An event handler is attached to every link and form in the page to set this variable to true, thus preventing the session from being terminated if the user is just submitting a form or clicking on a link.
function endSession() {
$.get("<whatever url will end your session>");
}
The session is terminated if the user closed the browser/tab or navigated away. In this case the global variable was not set to true and the script will do an AJAX call to whichever URL you want to end the session
This solution is server-side technology agnostic. It was not exaustively tested but it seems to work fine in my tests
Please refer the below steps:
First create a page SessionClear.aspx and write the code to clear session
Then add following JavaScript code in your page or Master Page:
<script language="javascript" type="text/javascript">
var isClose = false;
//this code will handle the F5 or Ctrl+F5 key
//need to handle more cases like ctrl+R whose codes are not listed here
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if(keycode == 116)
{
isClose = true;
}
}
function somefunction()
{
isClose = true;
}
//<![CDATA[
function bodyUnload() {
if(!isClose)
{
var request = GetRequest();
request.open("GET", "SessionClear.aspx", true);
request.send();
}
}
function GetRequest() {
var request = null;
if (window.XMLHttpRequest) {
//incase of IE7,FF, Opera and Safari browser
request = new XMLHttpRequest();
}
else {
//for old browser like IE 6.x and IE 5.x
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
return request;
}
//]]>
</script>
Add the following code in the body tag of master page.
<body onbeforeunload="bodyUnload();" onmousedown="somefunction()">
I do it like this:
$(window).bind('unload', function () {
if(event.clientY < 0) {
alert('Thank you for using this app.');
endSession(); // here you can do what you want ...
}
});
window.onbeforeunload = function () {
$(window).unbind('unload');
//If a string is returned, you automatically ask the
//user if he wants to logout or not...
//return ''; //'beforeunload event';
if (event.clientY < 0) {
alert('Thank you for using this service.');
endSession();
}
}
Not perfect but best solution for now :
var spcKey = false;
var hover = true;
var contextMenu = false;
function spc(e) {
return ((e.altKey || e.ctrlKey || e.keyCode == 91 || e.keyCode==87) && e.keyCode!=82 && e.keyCode!=116);
}
$(document).hover(function () {
hover = true;
contextMenu = false;
spcKey = false;
}, function () {
hover = false;
}).keydown(function (e) {
if (spc(e) == false) {
hover = true;
spcKey = false;
}
else {
spcKey = true;
}
}).keyup(function (e) {
if (spc(e)) {
spcKey = false;
}
}).contextmenu(function (e) {
contextMenu = true;
}).click(function () {
hover = true;
contextMenu = false;
});
window.addEventListener('focus', function () {
spcKey = false;
});
window.addEventListener('blur', function () {
hover = false;
});
window.onbeforeunload = function (e) {
if ((hover == false || spcKey == true) && contextMenu==false) {
window.setTimeout(goToLoginPage, 100);
$.ajax({
url: "/Account/Logoff",
type: 'post',
data: $("#logoutForm").serialize(),
});
return "Oturumunuz kapatıldı.";
}
return;
};
function goToLoginPage() {
hover = true;
spcKey = false;
contextMenu = false;
location.href = "/Account/Login";
}
It is not possible to kill the session variable, when the machine unexpectly shutdown due to power failure. It is only possible when the user is idle for a long time or it is properly logout.
For browser close you can put below code into your web.config :
<system.web>
<sessionState mode="InProc"></sessionState>
</system.web>
It will destroy your session when browser is closed, but it will not work for tab close.
Use this:
window.onbeforeunload = function () {
if (!validNavigation) {
endSession();
}
}
jsfiddle
Prevent F5, form submit, input click and Close/kill the session when the browser or tab is closed, tested in ie8+ and modern browsers, Enjoy!

Resources