Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter : Avoid using `forEach` with a function literal

Tags:

flutter

dart

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.

like image 971
delaram Avatar asked Jun 22 '21 16:06

delaram


Video Answer


1 Answers

AVOID using forEach with a function literal.

BAD:

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

GOOD:

for (var document in snapshot.docs) {
  // Rest of your code
}
like image 91
Sifat Amin Avatar answered Oct 18 '22 20:10

Sifat Amin