Repository: flutter
Issue: Repository disappears from context after a call to google_sign_in package
Labels: platform-android,a: quality,p: google_sign_in,package,P2,team-android,triaged-android

If I comment out this code from `LoginEvent` then it works.

```dart
GoogleSignInAccount _account = await _googleSignIn.signIn();
GoogleSignInAuthentication _auth = await _account.authentication;
String _token = _auth.accessToken;
```

Also If I create a new variable before `_googleSignIn.signIn()` which has assigned `getStorage` result it works either.
**Valid `LoginEvent` class:**
```
class LoginEvent extends AuthEvent {
  BuildContext context;
  LoginEvent({@required this.context});
  Future<AuthState> run() async {
    var _storage = getStorage(context: context);
    GoogleSignInAccount _account = await _googleSignIn.signIn();
    GoogleSignInAuthentication _auth = await _account.authentication;
    String _token = _auth.accessToken;
    try {
      await _storage.save(_token);
    } on FlutterError catch (error) {
      return AuthState(
        isAuthorized: false,
        inProgress: false,
        isLoaded: true,
        errorMessage: error.message.toString(),
      );
    }
    return AuthState(
      isAuthorized: _token != null && _token.isNotEmpty,
      inProgress: false,
      isLoaded: true,
      errorMessage: null,
    );
  }
}
``` 

It looks like the `context` rebuilds after `_googleSignIn` call.

I have these additional packages in my `pubspec.yaml`:
```
google_sign_in: ^4.1.4
flutter_secure_storage: ^3.3.1+1
flutter_bloc: ^3.2.0
```

**Full Error message:**

```
I/flutter (20947): Looking up a deactivated widget's ancestor is unsafe.
I/flutter (20947): At this point the state of the widget's element tree is no longer stable.
I/flutter (20947): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
E/AccessibilityBridge(20947): VirtualView node must not be the root node.
```

**To reproduce the problem you have to click "Login" button and try to login by Google account.**

<details>
  <summary>Invalid code sample</summary>

```dart
import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:google_sign_in/google_sign_in.dart';

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    'email',
  ],
);

void main() {
  return runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RepositoryProvider<UserStorage>(
      create: (context) => UserStorage(),
      child: BlocProvider<AuthBloc>(
        create: (context) => AuthBloc(context: context),
        child: BlocBuilder<AuthBloc, AuthState>(
          builder: (BuildContext context, AuthState state) {
            return MaterialApp(
              title: 'Test App',
              theme: ThemeData(
                primarySwatch: Colors.blue,
              ),
              home: homePage(state),
              builder: (BuildContext context, Widget widget) {
                if (state.errorMessage != null &&
                    state.errorMessage.isNotEmpty) {
                  print(state.errorMessage);
                  return buildError(context, state.errorMessage);
                }
                return widget;
              },
            );
          },
        ),
      ),
    );
  }

  Widget homePage(AuthState state) {
    if (!state.isLoaded) {
      return CircularProgressIndicator();
    }
    if (state.isAuthorized && !state.inProgress) {
      return MyHomePage(state.isAuthorized);
    } else if (!state.isAuthorized && state.inProgress) {
      return Center(
        child: CircularProgressIndicator(),
      );
    } else {
      return MyHomePage(state.isAuthorized);
    }
  }
}

class MyHomePage extends StatelessWidget {
  final bool isLoggedIn;
  MyHomePage(this.isLoggedIn, {Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              color: Colors.blue,
              onPressed: () => isLoggedIn
                  ? context.bloc<AuthBloc>().onLogout(context: context)
                  : context.bloc<AuthBloc>().onLogin(context: context),
              child: Text(isLoggedIn ? 'Logout' : 'Login'),
            ),
            Text(
              isLoggedIn ? 'Loggedin' : 'Not loggedin',
            ),
          ],
        ),
      ),
    );
  }
}

Widget buildError(BuildContext context, String errorMessage) {
  return Scaffold(
    backgroundColor: Colors.indigo,
    body: Padding(
      padding: EdgeInsets.all(20.0),
      child: ListView(
        children: <Widget>[
          Icon(Icons.mood_bad, color: Colors.white, size: 80.0),
          SizedBox(height: 20.0),
          Text(
            errorMessage,
            style: TextStyle(color: Colors.white),
          ),
        ],
      ),
    ),
  );
}

class AuthState {
  final bool inProgress;
  final bool isAuthorized;
  final bool isLoaded;
  final String errorMessage;

  const AuthState({
    @required this.inProgress,
    @required this.isAuthorized,
    @required this.isLoaded,
    @required this.errorMessage,
  });

  factory AuthState.initial() => AuthState(
        inProgress: false,
        isAuthorized: false,
        isLoaded: false,
        errorMessage: null,
      );
}

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  @override
  AuthState get initialState => AuthState.initial();

  AuthBloc({@required BuildContext context}) {
    _onCreate(context: context);
  }

  void _onCreate({@required BuildContext context}) => add(
        CreateEvent(context: context),
      );

  void onLogin({@required BuildContext context}) => add(
        LoginEvent(context: context),
      );

  void onLogout({@required BuildContext context}) => add(
        LogoutEvent(context: context),
      );

  @override
  Stream<AuthState> mapEventToState(AuthEvent event) async* {
    if (event is CreateEvent) {
      yield await event.run();
    } else if (event is LoginEvent) {
      yield AuthState(
        inProgress: true,
        isAuthorized: false,
        isLoaded: true,
        errorMessage: null,
      );
      yield await event.run();
    } else if (event is LogoutEvent) {
      yield AuthState(
        inProgress: true,
        isAuthorized: false,
        isLoaded: true,
        errorMessage: null,
      );
      yield await event.run();
    }
  }
}

abstract class AuthEvent {
  Future<AuthState> run();

  UserStorage getStorage({@required BuildContext context}) {
    return context.repository<UserStorage>();
  }
}

class CreateEvent extends AuthEvent {
  BuildContext context;
  CreateEvent({@required this.context});
  Future<AuthState> run() async {
    String _token;
    _token = await getStorage(context: context).token;
    return AuthState(
      isAuthorized: _token != null && _token.isNotEmpty,
      inProgress: false,
      isLoaded: true,
      errorMessage: null,
    );
  }
}

class LoginEvent extends AuthEvent {
  BuildContext context;
  LoginEvent({@required this.context});
  Future<AuthState> run() async {
    GoogleSignInAccount _account = await _googleSignIn.signIn();
    GoogleSignInAuthentication _auth = await _account.authentication;
    String _token = _auth.accessToken;
    try {
      await getStorage(context: context).save(_token);
    } on FlutterError catch (error) {
      return AuthState(
        isAuthorized: false,
        inProgress: false,
        isLoaded: true,
        errorMessage: error.message.toString(),
      );
    }
    return AuthState(
      isAuthorized: _token != null && _token.isNotEmpty,
      inProgress: false,
      isLoaded: true,
      errorMessage: null,
    );
  }
}

class LogoutEvent extends AuthEvent {
  final BuildContext context;
  LogoutEvent({@required this.context});
  Future<AuthState> run() async {
    while (Navigator.of(context).canPop()) {
      Navigator.of(context).pop();
    }
    Navigator.of(context).pushNamedAndRemoveUntil(
        Navigator.defaultRouteName, (Route<dynamic> route) => false);

    await _googleSignIn.signOut();
    getStorage(context: context).remove();
    return AuthState(
      inProgress: false,
      isAuthorized: false,
      isLoaded: true,
      errorMessage: null,
    );
  }
}

class UserStorage {
  static const _token_key = 'token';

  Future<String> get token async {
    final _storage = FlutterSecureStorage();

    return await _storage.read(key: _token_key);
  }

  Future<void> save(String token) async {
    final _storage = FlutterSecureStorage();
    await _storage.write(key: _token_key, value: token);
  }

  Future<void> remove() async {
    final _storage = FlutterSecureStorage();
    await _storage.deleteAll();
  }
}
```

</details>

With `flutter_facebook_login` (v. 3.0.0) I have the same problem. It seems to me that there is something wrong with context after launching WebView or similar things.

<details>
  <summary>flutter doctor -v</summary>

> [√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.19559.1000], locale pl-PL)
> • Flutter version 1.12.13+hotfix.8 at C:\src\flutter
> • Framework revision 0b8abb4724 (2 weeks ago), 2020-02-11 11:44:36 -0800
> • Engine revision e1e6ced81d
> • Dart version 2.7.0
> 
> 
> [√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
> • Android SDK at C:\Users\owcza\AppData\Local\Android\sdk
> • Android NDK location not configured (optional; useful for native profiling support)
> • Platform android-29, build-tools 29.0.2
> • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
> • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
> • All Android licenses accepted.
> 
> [√] Android Studio (version 3.6)
> • Android Studio at C:\Program Files\Android\Android Studio
> • Flutter plugin version 43.0.2
> • Dart plugin version 192.7761
> • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
> 
> [√] Connected device (1 available)
> • LG H930 • LGH930106dd0e5 • android-arm64 • Android 9 (API 28)
> 
> • No issues found!

</details>

[flutter run --verbose with 3rd party packages.txt](https://github.com/flutter/flutter/files/4257859/flutter.run.--verbose.with.3rd.party.packages.txt)