Skip to content

Conversation

@srivats22
Copy link

This PR Fixes: flutter/flutter#167410, where _initCalled was being performed twice on the web

Based on the discussion comments I have removed the calles to _initCalled in the google_sign_in_web package

Pre-Review Checklist

If you need help, consider asking for advice on the #hackers-new channel on Discord.

Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the gemini-code-assist bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.

Footnotes

  1. Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling. 2 3

@srivats22 srivats22 requested a review from ditman as a code owner July 29, 2025 15:15
@flutter-dashboard
Copy link

It looks like this pull request may not have tests. Please make sure to add tests or get an explicit test exemption before merging.

If you are not sure if you need tests, consider this rule of thumb: the purpose of a test is to make sure someone doesn't accidentally revert the fix. Ask yourself, is there anything in your PR that you feel it is important we not accidentally revert back to how it was before your fix?

Reviewers: Read the Tree Hygiene page and make sure this patch meets those guidelines before LGTMing.If you believe this PR qualifies for a test exemption, contact "@test-exemption-reviewer" in the #hackers channel in Discord (don't just cc them here, they won't see it!). The test exemption team is a small volunteer group, so all reviewers should feel empowered to ask for tests, without delegating that responsibility entirely to the test exemption group.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

The pull request removes the _initCalled completer, which introduces a race condition. The init method should be made idempotent to handle being called multiple times. The CHANGELOG.md entry should be a complete sentence ending with a period.

@stuartmorgan-g stuartmorgan-g self-requested a review July 29, 2025 18:23
@srivats22
Copy link
Author

srivats22 commented Jul 29, 2025

Hi,

any idea or pointers on how to fix this:

The following TestFailure was thrown running a test (but after
the test had completed):
Expected: throws <Instance of 'StateError'>
  Actual: <Closure: () => Future<Null> from: () => {
                            let t$goto = 0, t$completer =
async._makeAsyncAwaitCompleter(T.Null());
                            var t$36asyncBody =
async._wrapJsFunctionForAsync((t$errorCode, t$result) => {
                              if (t$errorCode === 1) return
async._asyncRethrow(t$result, t$completer);
                              while (true)
                                switch (t$goto) {
                                  case 0:
                                    // Function start
                                    t$goto = 2;
                                    return
async._asyncAwait(t$36$35plugin$35get().disconnect(C[8] ||
CT.C8), t$36asyncBody, t$completer);
                                  case 2:
                                    // returning from await.
                                    // implicit return
                                    return
async._asyncReturn(null, t$completer);
                                }
                            });
                            return
async._asyncStartSync(t$36asyncBody, t$completer);
                          }>
   Which: returned a Future that emitted <null>

When the exception was thrown, this was the stack:

its failing for the same reason in 3 of the tests and the repo check I know the issue which I will fix...

@stuartmorgan-g
Copy link
Collaborator

I'm not sure I understand the question. The expectations that check that calling a method without calling init throws a StateError are failing because you removed the code that throws the StateError if a method is called without calling init.

@srivats22
Copy link
Author

Oh so the changes in the PR is incorrect? Or something else needs to change?

@stuartmorgan-g
Copy link
Collaborator

Tests that expect that the web implementation asserts init completion everywhere are no longer valid if the web implementation no longer asserts init completion. Intentional behavioral changes often require changing tests.

@srivats22
Copy link
Author

Understood let me look at the code and see where the initCompleted is still be called in the test and remove those... Last I checked wasn't able to find any

@stuartmorgan-g
Copy link
Collaborator

From triage: Is this ready for review?

@srivats22
Copy link
Author

Yes its ready for review looks like I might need to fix the conflicts which I will get to

@stuartmorgan-g stuartmorgan-g added the triage-web Should be looked at in web triage label Aug 19, 2025
@mdebbar mdebbar requested review from mdebbar and removed request for ditman August 20, 2025 18:15
Copy link
Contributor

@mdebbar mdebbar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for contributing this fix!

Some thoughts:

When the app calls init() twice (potentially with different params), it becomes a tricky situation. We already have the first init() in flight while the second init() is being executed.

I think we should let both init() calls continue to completion. Any calls to await initialized; should await the latest init() call.

init(InitParameters(clientId: 111));
init(InitParameters(clientId: 222));
await initialized;
// At this point, the plugin should be ready with clientId 222.

@stuartmorgan-g what do other platforms do in this case?

@srivats22
Copy link
Author

I made the changes based on what was put in the issue... What I got from it was since the logic has been moved outside the package the code for init seems redundant... I might have miss understood let me take a look based on the comments and try and incorporate it

@stuartmorgan-g
Copy link
Collaborator

stuartmorgan-g commented Aug 21, 2025

@stuartmorgan-g what do other platforms do in this case?

Nothing; in the new version of google_sign_in, clients explicitly call an initialize method (rather than it being an internal, implicit thing on most platforms, but semi-exposed on web, as was the case before), and the docs say they must do so exactly once. It's a programming error by the client to write the code you've shown there.

If we think clients need explicit Errors when doing the wrong thing, that should be added to the app-facing package, rather than handled in each implementation. This code is a legacy of the exposed-for-web nature of the previous init code.

(Also, clients should basically never call the platform interface methods directly. That's not how most federated plugins are designed.)

@@ -1,3 +1,7 @@
## 1.0.1

* Fixes Bad state: Future already completed on the web.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sounds like there was a bug in the plugin that was fixed, which is not the case. This should say something like "Removes initialization checks, since initialization handling has moved to the app-facing package."

/// This ensures that the SDK has been loaded, and that the `init` method
/// has finished running.
@visibleForTesting
Future<void> get initialized {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method should just be removed.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will work on it and push the updated changes by today if possible

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing the function completely won't work cause the renderButton uses the initialized function as the future

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That code is wrong now though; initialized is now equivalent to just _jsSdkLoadedFuture in this PR, but the code in renderButton that is being guarded requires _gisSdkClient to be non-null, and there's no order guarantee between those two things.

If we want to keep renderButton callable before initialization (I'm skeptical that that's actually important with the new API structure), then the internals need to be restructured to make that actually work. But that can be done with an internal future that doesn't have a getter wrapping it.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood so how should I proceed??

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mdebbar Do you want renderButton to be callable before the plugin client has run initialize at the app-facing package level?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From triage: Ping @mdebbar on the question above.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked at iOS and Android implementations and I didn't see explicit errors being thrown if init() is called twice.

The documentation says: or calling this method more than once, will result in undefined behavior. I would say throwing an error qualifies as "undefined behavior" :)

Here's my suggestion:

  1. Make initialized a private property _initialized to be used by methods in this file, and returned from init() to be used by users.
  2. Throw if init() is called more than once.
  3. _gisSdkClient should become late final GisSdkClient _gisSdkClient; so that it can only be set once, and it throws if accessed before initialization.

Copy link
Contributor

@mdebbar mdebbar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the delay in my response. I gave this some more thought and looked at the documentation and other platforms. See my suggestion in the comment below.

/// This ensures that the SDK has been loaded, and that the `init` method
/// has finished running.
@visibleForTesting
Future<void> get initialized {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked at iOS and Android implementations and I didn't see explicit errors being thrown if init() is called twice.

The documentation says: or calling this method more than once, will result in undefined behavior. I would say throwing an error qualifies as "undefined behavior" :)

Here's my suggestion:

  1. Make initialized a private property _initialized to be used by methods in this file, and returned from init() to be used by users.
  2. Throw if init() is called more than once.
  3. _gisSdkClient should become late final GisSdkClient _gisSdkClient; so that it can only be set once, and it throws if accessed before initialization.

@srivats22
Copy link
Author

srivats22 commented Oct 27, 2025

Thank you, I will work on it with the directions provided and update the PR

Comment on lines 112 to 116
if (_initCalled.isCompleted) {
throw StateError(
'init() has already been called. Calling init() more than once results in undefined behavior.',
);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will prevent:

await plugin.init(...);
await plugin.init(...); // This will throw.

But will not prevent this:

plugin.init(...);
plugin.init(...); // This will NOT throw.

One way to solve it is to introduce a new boolean:

Suggested change
if (_initCalled.isCompleted) {
throw StateError(
'init() has already been called. Calling init() more than once results in undefined behavior.',
);
}
if (_isInitCalled) {
throw StateError(
'init() has already been called. Calling init() more than once results in undefined behavior.',
);
}
_isInitCalled = true;

@visibleForTesting
Future<void> get initialized {
_assertIsInitCalled();
Future<void> get _initialized {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid the unnecessary creation of new futures:

Future<void> get _initialized => _initCalled!.future;

@srivats22
Copy link
Author

Is it ok if I close this PR and open a new one?

@stuartmorgan-g
Copy link
Collaborator

@srivats22 What would the goal of doing that be? Making it harder to find all the review context makes continuing the review much harder.

@srivats22
Copy link
Author

@srivats22 What would the goal of doing that be? Making it harder to find all the review context makes continuing the review much harder.

Oh ok no worries I will just push to this... Was just thinking the number of commits were increasing hence...

@stuartmorgan-g
Copy link
Collaborator

From triage: @srivats22 Are you still planning on updating this PR based on the review feedback?

@srivats22
Copy link
Author

From triage: @srivats22 Are you still planning on updating this PR based on the review feedback?

Hi,

yes I am still working on it... I had posted a question:
Quick question on this, should _isInitCalled be a local boolean? or how should I procceed on it? Once I get the answer I will try and finalize it by this week

@stuartmorgan-g
Copy link
Collaborator

I had posted a question: Quick question on this, should _isInitCalled be a local boolean?

I don't see anywhere in the discussion above where you asked that; the only comment since the last review was when you asked about creating a new PR.

You'll need to provide more context for the question, since I'm not sure what you mean. I don't see how a local variable would be relevant to the previous discussion.

@srivats22
Copy link
Author

I had posted a question: Quick question on this, should _isInitCalled be a local boolean?

I don't see anywhere in the discussion above where you asked that; the only comment since the last review was when you asked about creating a new PR.

You'll need to provide more context for the question, since I'm not sure what you mean. I don't see how a local variable would be relevant to the previous discussion.

Screenshot 2025-12-03 at 9 48 14 AM Sorry I had accidently put it as a review comment have attached a screenshot of the same

@mdebbar
Copy link
Contributor

mdebbar commented Dec 3, 2025

@srivats22 yes _isInitCalled should be private and serve a single purpose: detect when init() is called more than once.

Copy link
Contributor

@mdebbar mdebbar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code changes look good to me! Thanks for addressing all the concerns and being patient with us :)

My remaining comments are about CHANGELOG and code comments.

@srivats22
Copy link
Author

How do I fix the build failures?

Comment on lines 70 to 81
testWidgets('throws if init is called twice', (_) async {
await plugin.init(
const InitParameters(clientId: 'some-non-null-client-id'),
);

expect(plugin.initialized, completes);
// Calling init() a second time should throw state error
expect(
() => plugin.init(
const InitParameters(clientId: 'some-non-null-client-id'),
),
throwsStateError,
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add another test for multiple synchronous calls:

    testWidgets('throws if init is called twice synchronously', (_) async {
      final firstInit = plugin.init(
        const InitParameters(clientId: 'some-non-null-client-id'),
      );

      // Calling init() a second time synchronously should throw state error
      expect(
        () => plugin.init(
          const InitParameters(clientId: 'some-non-null-client-id'),
        ),
        throwsStateError,
      );
      
      await firstInit;
    });

Comment on lines +1 to +3
## 1.1.1

* Throws a more actionable error when init is called more than once
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be combined with the items from NEXT section:

## 1.1.1

* Throws a more actionable error when init is called more than once
* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

p: google_sign_in platform-web triage-web Should be looked at in web triage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[google_sign_in_web] _initCalled completed twice

3 participants