title: Keeping Flutter dart stream open to watch for changes to a model
body: <p>I'm new to Flutter/Dart and trying to create a basic authentication service. My plain is to make my main application listen to a stream which will emit the user when authentication actions take place. This is how a lot of the Firebase examples work, the only difference is that I want to connect directly to my own API.</p>
  <p>To do this I've created an AuthService, but can't actually seem to get it working.</p>
  <pre class="lang-dart prettyprint-override"><code>void main() {
    runApp(MyApp());
  }
  
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Provider&lt;AuthService&gt;(
        create: (_) =&gt; AuthService(),
        child: MaterialApp(
          home: AuthWidget()
        )
      );
    }
  }
  
  class AuthWidget extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
  
      final authService = Provider.of&lt;AuthService&gt;(context);
      authService.getUser();
  
      // wrap the application in a Stream that watches for the authentication state
      // to change. On authentication state change,
      return StreamBuilder&lt;User&gt;(
          stream: authService.onAuthStateChanged,
          builder: (context, snapshot) {
            
            // check to ensure that the connectionState is active
            if (snapshot.connectionState == ConnectionState.active) {
              final user = snapshot.data;
              return user == null ? Login() : Home();
            }
  
            return Login();
          }
      );
    }
  }
  
  
  class AuthService {
  
    User currentUser;
  
    Future&lt;User&gt; getUser() {
      return Future.value(currentUser);
    }
  
    void login(User user) {
      currentUser = user;
    }
  
    void logout() {
      currentUser = null;
    }
  
    Stream&lt;User&gt; get onAuthStateChanged {
      return Stream.fromFuture(getUser());
    }
  }
  </code></pre>
  <h2>What I want to achieve</h2>
  <p>At the top level <code>MyApp</code>, I'd like to be able to listen for changes in authentication using the AuthProvider. I should be able to access the authentication provider anywhere, e.g.</p>
  <pre><code>final auth = Provider.of&lt;AuthService&gt;(context, listen: false);
  
  // log the user in
  auth.login(user);
  
  // log the user out
  auth.logout(user);
  
  // get the current authenticated user
  auth.getUser();
  </code></pre>
  <p>And use this to manage the application. The problem I am having with my existing code is that the Stream status is instantly marked as done, so no further changes are ever emitted from the <code>onAuthStateChanged</code>. I actually need my <code>AuthWidget</code> to continue listening throughout the lifetime of the application, so that I can respond to login/logout events and change the UI accordingly.</p>
  <p>Any help is greatly appreciated!</p>