flutterdart

Flutter : Avoid using `forEach` with a function literal


Hi everyone this is my whole method :

Future<void> init() async {
    FirebaseAuth.instance.userChanges().listen((user) {
      if (user != null) {
        _loginState = ApplicationLoginState.loggedIn;
        _guestBookSubscription = FirebaseFirestore.instance
            .collection('guestbook')
            .orderBy('timestamp', descending: true)
            .limit(3)
            .snapshots()
            .listen((snapshot) {
          _guestBookMessages = [];
          snapshot.docs.forEach((document) {
            _guestBookMessages.add(
              GuestBookMessage(
                name: document.data()['name'] as String,
                message: document.data()['text'] as String,
              ),
            );
          });
          notifyListeners();
        });
      } else {
        _loginState = ApplicationLoginState.loggedOut;
        _guestBookMessages = [];
        _guestBookSubscription?.cancel();
      }
      notifyListeners();
    });
  }

the part that dart complains about is this one :

snapshot.docs.forEach((document) {
            _guestBookMessages.add(
              GuestBookMessage(
                name: document.data()['name'] as String,
                message: document.data()['text'] as String,
              ),
            );
          });

how can I change this method without ruining the whole functionality ? Im just looking for a way that makes dart happy . I appreciate your help in advance.


Solution

  • AVOID using forEach with a function literal.

    AVOID:

    snapshot.docs.forEach((document) {
      ...
    });
    

    GOOD:

    for (final document in snapshot.docs) {
      // Rest of your code
    }