Provider Throw Errors in InitState. Provider.of<SomeProvider>(context) - dart

How do I access the context for the Provider in the initState
I keep getting the error
flutter: The following assertion was thrown building Builder:
flutter: inheritFromWidgetOfExactType(_Provider<ProductProvider>) or inheritFromElement() was called before
flutter: _ProductDetailsPageState.initState() completed.
Whenever I run the code below
if (Provider.of<ProductProvider>(context).selectedProduct == null) {
product = Product();
product.isReturnable = true;
product.isActive = true;
product.premiumType = "None Selected";
product.category = 'None Selected';
product.principal = 'None Selected';
} else {
product = Provider.of<ProductProvider>(context).selectedProduct;
}
N.B. the above code worked perfectly when I used the Scoped Model, however, user the Provider Model and Package throws an exception.
What I need it to access the provider before the build process, because contents of the provider are needed to build the UI.

Provider.of<ProductProvider>(context, listen: false).selectedProduct and ensure there are no NotifyListeners in the initState call.

Try to postpone this call with Future.delayed(...)

Use Simon's AfterLayout package https://pub.dev/packages/after_layout and call it in the function you need to implement. It will be called after Build() has been run

Related

Orchestrator function code awaits on a task that was not created by a DurableOrchestrationContext method

I have the following code in Orchestrator function:
var sourceGroups = await context.CallActivityAsync<AzureADGroup[]>(nameof(SourceGroupsReaderFunction), new SourceGroupsReaderRequest { SyncJob = syncJob, RunId = runId });
if (sourceGroups.Length == 0)
{
await _log.LogMessageAsync(new LogMessage
{
RunId = runId,
Message =
$"None of the source groups in {syncJob.Query} were valid guids. Marking job as errored."
});
await _calculator.SendEmailAsync(syncJob, runId, SyncDisabledNoValidGroupIds, new[] { syncJob.Query });
}
On running this, I see the following error:
Function 'OrchestratorFunction (Orchestrator)' failed with an error. Reason: System.InvalidOperationException: Multithreaded execution was detected. This can happen if the orchestrator function code awaits on a task that was not created by a DurableOrchestrationContext method. More details can be found in this article https://learn.microsoft.com/en-us/azure/azure-functions/durable-functions-checkpointing-and-replay#orchestrator-code-constraints.
What am I missing?

Google Sign-In With Flutter: Error Code -4

I currently try to implement google_sign_in package in Flutter (https://pub.dartlang.org/packages/google_sign_in).
For this, I followed the example of their repository (https://github.com/flutter/plugins/blob/master/packages/google_sign_in/lib/google_sign_in.dart).
In that example in "initState" is a call signInSilently.
#override
void initState() {
super.initState();
_googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
setState(() {
_currentUser = account;
loggedIn = true;
});
});
loggedIn = false;
_googleSignIn.signInSilently();
}
I tried this code in iOS. On my first App Start, it worked well. But since I logged out I get an error here all the time I restart my app.It is the following PlatformException:
PlatformException(sign_in_required, com.google.GIDSignIn, The operation couldn’t be completed. (com.google.GIDSignIn error -4.))
I found in question Google Sign-In Error -4 that the error code is because of a missing Auth in Keychain.
The solution while swift programming is to call the method * hasAuthInKeychain* before the try to signInSilently. My problem is that the GoogleSignIn class in the flutter package has no function named like this.
Is there another call I need to run with this package to be sure I can try a silent log in? Or am I doing something wrong to get this message or is there even the possibility of catching this error?
Edit
I tried Marcel's solution, too. Somehow it is not catching the PlatfromException.
I do not know if this will help: signInSilently() is calling a method in which there is a the following call (google_sign_in.dart, line 217):
await channel.invokeMethod(method)
In platform_channel.dart there is a call
codec.decodeEnvelope(result);
The platform exception gets thrown in here.
if (errorCode is String && (errorMessage == null || errorMessage is String) && !buffer.hasRemaining)
throw PlatformException(code: errorCode, message: errorMessage, details: errorDetails);
else
throw const FormatException('Invalid envelope');
Edit 2
Since I just run my app and not started it in debug mode it somehow works again without throwing an exception. I do not know how this affects the code and why I got this exception. I can also run the code in debug mode again.
Since then I had the exception once again. Again I restarted android studio and runned the application once without debug mode.
You could just check if the sign in failed by handling the PlatformException like this:
void _setUpGoogleSignIn() async {
try {
final account = await _googleSignIn.signInSilently();
print("Successfully signed in as ${account.displayName}.");
} on PlatformException catch (e) {
// User not signed in yet. Do something appropriate.
print("The user is not signed in yet. Asking to sign in.");
_googleSignIn.signIn();
}
}
This is one way to catch the error and run _googleSignIn.signIn();
GoogleSignInAccount googleSignInAccount = await googleSignIn
.signInSilently(suppressErrors: false)
.catchError((dynamic error) async {
GoogleSignInAccount googleSignInAccount =
await _googleSignIn.signIn();
});
In my case, I did not want the user to see the login window automatically. In this case I changed from signIn to signOut. This way, I send the user to another view with an explanatory message and a login button.
GoogleSignInAccount googleSignInAccount = await googleSignIn
.signInSilently(suppressErrors: false)
.catchError((dynamic error) async {
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signOut();
return googleSignInAccount;
});

Editing resolution of JIRA issue using Transition throws exception

I have two JIRA project for eg. DEV and CLIENT. I want to set the resolution of issue in CLIENT project to DONE when the resolution of issue in DEV project changes to DONE.
For this I have done following code :
public void changeTransition(com.atlassian.jira.issue.Issue devIssue, Issue clientIssue, JiraRestClient restClient) {
IssueRestClient issueClient = restClient.getIssueClient();
Iterable<Transition> transitions = issueClient.getTransitions(clientIssue.getTransitionsUri()).claim();
final Transition doneIssueTransition = getTransitionByName(transitions, "Done"); //this returns done Transition
if (doneIssueTransition != null) {
ImmutableList.Builder<FieldInput> builder = ImmutableList.builder();
builder.add(new FieldInput(IssueFieldId.RESOLUTION_FIELD, ComplexIssueInputFieldValue.with("name", devIssue.getResolution().getName())));
ImmutableList<FieldInput> fieldInputs = builder.build();
TransitionInput transitionInput = new TransitionInput(doneIssueTransition.getId(), fieldInputs, prepareComment(devIssue));
issueClient.transition(clientIssue.getTransitionsUri(), transitionInput).claim();
}
}
The exception that I get is :
Field 'resolution' cannot be set. It is not on the appropriate screen, or unknown.
is there anything wrong with the code? what this exception signifies? what changes should I make to get this resolved?

C# - Xamarin - HttpClient - Operation is not valid due to the current state of the object - iOS

I'm working on a cross platform library that makes HTTP requests. It's working fine on Android, but when I try to use it on iOS I'm getting an exception and I can't figure out how to fix it.
Here is my code:
// method from cross platform library
Task.Factory.StartNew(delegate
{
try
{
var client = new HttpClient();
// some other setup stuff
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.post, "http://myurl.com...");
var task = client.SendAsync(request);
task.Wait(); // Exception thrown on this line
var response = task.Result;
var responseString = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
}
}
On task.Wait(); I get a System.AggregateException with an inner exception of System.InvalidOperationException that says Operation is invalid due to the current state of the object.
Trying to find some solutions, I found that the issue could be cause by calling this on the UI thread. But that's the whole point of wrapping this all in Task.Factory.StartNew.
I've tried everything I know to do and have yet to solve the issue. Any help would be very appreciated.
Edit:
I decided to try my solution on an iPhone simulator. It's an iPhone 6 simulator running iOS 10. My physical device is the same. It works on the simulator, but not the physical device for some reason... very strange.
Edit 2:
Thanks to #YuriS for finding a solution.
From: https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec
What you can do is:
1) Go to References of ios Project
2) Edit References
3) Check 'System.Net.Http'
Behaviour for android is the same.
There can be few problems described here:
https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec
https://bugzilla.xamarin.com/show_bug.cgi?id=17936
"Operation is not valid" error at Xamarin.iOS project with HttpClient
http://motzcod.es/post/78863496592/portable-class-libraries-httpclient-so-happy
Seems all post pointing on System.Net.Http
Regardless of the problem there is a better ways doing this.One of them:
public static async Task PostRequest()
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://myuri");
//request.Headers.Add("", "");
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
}
}
If you want to wait till function completes you call
await PostRequest();
If you don't need to wait then just omit "await" in the call or use
PostRequest.ContinueWith((t)=>
{
});
Also you need to handle an exception within the function, so probably returning just Task is not the best. I was just basing my answer on original function signature

ObjectStore put syntax

I'm having trouble with the new syntax (r18915) for idb.ObjectStore.put. Could someone please help?
example is below which results in error as follows :
AsyncError: ‘Error:DataError: DOM IDBDatabase Exception 0’
Stack trace: #0 ObjectStore._put_2(file:///E:/b/build/slave/dartium-win-full-trunk/build/src/build/Release/obj/
global_intermediate/webkit/bindings/dart/indexed_db/ObjectStore.dart:141:3) #1
ObjectStore.$dom_put(file:///E:/b/build/slave/dartium-win-full-trunc/build/src/build/Release/obj/
global_intermediate/webkit/bindings/dart/indexed_db/ObjectStore.dart:137:18) #2
ObjectStore.put(file:///E:/b/build/slave/dartium-win-full-trunc/build/src/build/Release/obj/
global_intermediate/webkit/bindings/dart/indexed_db/ObjectStore.dart:9:27)
The code I'm using which was working but has been modified for new release as follows :
Future fDbAddOrUpdateClient(String sKey1, ClassClientData clClientData) {
idb.Transaction oDbTxn = ogDb1.transaction(sgStoreClient, 'readwrite');
idb.ObjectStore oDbStoreClient = oDbTxn.objectStore(sgStoreClient);
Completer completer = new Completer();
var oDbReqPut = oDbStoreClient.put(
{'sKey': sKey1,
'sNameTitle' : clClientData.sNameTitle,
'sNameFamily' : clClientData.sNameFamily,
'sNameGiven1' : clClientData.sNameGiven1,
'sNameGiven2' : clClientData.sNameGiven2
})
.then((val){
completer.complete(val);
return;
})
.catchError((e){
window.alert("${e}");
return;
});
}
Apart from the future you specify your function returns but never does, only a completed value (as mentioned in other comment), the future syntax appears correct. The error itself actually indicates that the data being passed to your objectstore.put command is invalid.
See IndexedDB Exceptions. You may need to verify the data that is being passed to the map.
Thanks for the help. The main problem appeared to be with Database not opening or something related such as ObjectStore not being created, but no error shown.
Hopefully the following is better code (r19425) :
Future future = fDbAddOrUpdateClient(sKey, clClientData)
.catchError((oError) => window.alert("${oError}"));
}
Future fDbAddOrUpdateClient(String sKey1, ClassClientData clClientData) {
idb.Transaction oDbTxn = ogDb1.transaction(sgStoreClient, 'readwrite');
idb.ObjectStore oDbStoreClient = oDbTxn.objectStore(sgStoreClient);
return oDbStoreClient.put(fMapClient(sKey1, clClientData));
}

Resources