title: Getting data from Firebase offline database (Flutter)
body: <p>I have an app which is checking only one value is exist or not when get to second page and build ui according to this info, if I do that with regular way it takes time and getting an null error for a sec before page build also I have to read database too oftenly than I want, so is there any way to check data from only offline database while connected to internet? </p>
  
  <p>Edit:</p>
  
  <p>As summary, I have a HomePage and it shows whole list belongs to user recorded as favorite with a ListView.Builder and user only see and able to remove them from this screen, the only way to add anything to list is added from my second page, and I check the item added or not while building, if it's added my favorite button shape change and it remove when onpressed if it's not same button save it to favorite. You can check below codes(related parts)</p>
  
  <p>HomePage:</p>
  
  <pre><code>class MyFirstPage extends StatefulWidget {
    MyFirstPage({Key key, this.auth, this.userId, this.logoutCallback, this.user})
        : super(key: key);
  
    final BaseAuth auth;
    final VoidCallback logoutCallback;
    final String userId;
    final FirebaseUser user;
  
    static String routeName = "/MyFirstPage";
  
    @override
    _MyFirstPageState createState() =&gt; new _MyFirstPageState();
  }
  
  class _MyFirstPageState extends State&lt;MyFirstPage&gt; {
    String userId;
    List&lt;Movies&gt; _moviesList;
    Query _moviesQuery;
  
    final FirebaseDatabase _database = FirebaseDatabase.instance;
    final GlobalKey&lt;FormState&gt; formKey = GlobalKey&lt;FormState&gt;();
    StreamSubscription&lt;Event&gt; _onMoviesAddedSubscription;
    StreamSubscription&lt;Event&gt; _onMoviesChangedSubscription;
    AuthStatus authStatus;
  
    @override
    void initState() {
      // TODO: implement initState
      super.initState();
       _moviesList = new List();
      _moviesQuery = _database
          .reference()
          .child("movies")
          .orderByChild("userId")
          .equalTo(widget.userId);
      _onMoviesAddedSubscription = _moviesQuery.onChildAdded.listen(onEntryAdded);
      _onMoviesChangedSubscription =
          _moviesQuery.onChildChanged.listen(onEntryChanged);
      widget.auth.getCurrentUser().then((user) {
        setState(() {
          if (user != null) {
            userId = user?.uid;
          }
          authStatus =
          user?.uid == null ? AuthStatus.NOT_LOGGED_IN : AuthStatus.LOGGED_IN;
        });
      });
  
    }
  
  
    void dispose() {
      _onMoviesAddedSubscription.cancel();
      _onMoviesChangedSubscription.cancel();
      super.dispose();
    }
  
    onEntryChanged(Event event) {
      var oldEntry = _moviesList.singleWhere((entry) {
        return entry.key == event.snapshot.key;
      });
  
      setState(() {
        _moviesList[_moviesList.indexOf(oldEntry)] =
            Movies.fromSnapshot(event.snapshot);
      });
    }
  
    onEntryAdded(Event event) {
      setState(() {
        _moviesList.add(Movies.fromSnapshot(event.snapshot));
      });
    }
  
    signOut() async {
      try {
        await widget.auth.signOut();
        widget.logoutCallback();
      } catch (e) {
        print(e);
      }
    }
  
    updateMovies(Movies movies) {
      //Toggle completed
      movies.watched = !movies.watched;
      if (movies != null) {
        _database.reference().child("movies").set(movies.toJson());
      }
    }
  
    deleteMovies(String moviesId, int index) {
      _database.reference().child("movies").child(moviesId).remove().then((_) {
        print("Delete $moviesId successful");
        setState(() {
          _moviesList.removeAt(index);
        });
      });
    }
  
  ...
  ListView.builder(
          shrinkWrap: true,
          scrollDirection: Axis.horizontal,
          itemCount: _moviesList.length,
          itemBuilder: (BuildContext context, int index) {...}
  </code></pre>
  
  <p>SecondPage:</p>
  
  <pre><code>class MovieDetailPage extends StatefulWidget {
    MovieDetailPage({Key key, this.title, this.auth, this.userId, this.user})
        : super(key: key);
  
    final BaseAuth auth;
    final String userId;
    final FirebaseUser user;
    static String routeName = "/MovieDetailPage";
    final String title;
  
    @override
    _MovieDetailPageState createState() =&gt; _MovieDetailPageState();}
  
  class _MovieDetailPageState extends State&lt;MovieDetailPage&gt; {
    final GlobalKey&lt;InnerDrawerState&gt; _innerDrawerKey = GlobalKey&lt;InnerDrawerState&gt;();
    final GlobalKey&lt;RefreshIndicatorState&gt; _refreshIndicatorKey =
    new GlobalKey&lt;RefreshIndicatorState&gt;();
  
    Future&lt;void&gt; recorded(String idname) async{
      final dbRef = await FirebaseDatabase.instance.reference().child(
          "movies").orderByChild("unique").equalTo(idname).once();
      return dbRef;
    }
    String userId;
    final FirebaseDatabase _database = FirebaseDatabase.instance;
    final GlobalKey&lt;FormState&gt; formKey = GlobalKey&lt;FormState&gt;();
    List&lt;Movies&gt; _moviesList;
    AuthStatus authStatus;
  
  
    @override
    void initState() {
      // TODO: implement initState
      super.initState();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        WidgetsBinding.instance.addPostFrameCallback((_) =&gt;
            getNamePreferences().then(updateName));
      });
      _moviesList = new List();
      widget.auth.getCurrentUser().then((user) {
        if (user != null) {
          userId = user?.uid;
        }});
  
    }
  
  //I have a FutureBuilder for getting details
  
  FutureBuilder&lt;Payload&gt;(
            future:  getData(_name),
            builder: (context, snapshot) {
              if (snapshot.connectionState != ConnectionState.done &amp;&amp; firstRun == true)
                return Center(child: Image.asset("images/dice.gif"));
              if (snapshot.connectionState == ConnectionState.done)
                if (snapshot.hasError)
                {....
  
  // and I have a second FutureBuilder for my FAB because its change according to data
                    floatingActionButton:  FutureBuilder(
                            future: recorded(userId+snapshot.data.imdbId),
                            builder: (context, snapshots) {
                              return Container(
                                width: MediaQuery.of(context).size.width,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: &lt;Widget&gt;[
                                    FloatingActionButton(
                                        heroTag: 3,
                                        backgroundColor: Colors.blueGrey.withOpacity(0.4),
                                        onPressed: ()
                                        {
                                          Movies movies = new Movies(snapshot.data.imdbId, snapshot.data.originalTitle, snapshot.data.posterPath, snapshot.data.backdropPath, snapshot.data.releaseDate, snapshot.data.title, snapshot.data.voteAverage, snapshot.data.genres, false, userId, userId+snapshot.data.imdbId);
                                          snapshots.data.value == null ?
                                          _database.reference().child("movies").push().set(movies.toJson())
                                              :
                                          FirebaseDatabase.instance.reference()
                                              .child('movies')
                                              .orderByChild('unique')
                                              .equalTo(userId+snapshot.data.imdbId)
                                              .once()
                                              .then((DataSnapshot snapshot) {
                                            Map&lt;dynamic, dynamic&gt; children = snapshot.value;
                                            children.forEach((key, value) {
                                              FirebaseDatabase.instance.reference()
                                                  .child('movies')
                                                  .child(key)
                                                  .remove();
                                            });
                                          });
                                          setState(() {});
                                        },
                                        child: Icon(snapshots.data.value != null ? Icons.favorite : Icons.favorite_border )
                                    )
  
                                  ],
                                ),
                              );
                            }
                        ),
  
  </code></pre>