'flutter - infinite loop on a finite array

I don't understand why the result of my code is an infinite loop.

class _SearchUserState extends State<SearchUser> {
  List usernames = [];
 @override
  Widget build(BuildContext context) {
    var invitedBy = widget.snapshot.data()["invitedBy"];
    final FirebaseFirestore _firestore = FirebaseFirestore.instance;
    invitedBy.forEach((userId) async {
      try {
        var snap = await _firestore.collection('users').doc(userId).get();
        var username = snap.data()!["username"];
        print(username);
        setState(() {
          usernames.add(username);
        });
      } catch (err) {
        print(err);
      }
    });
 Text("invitedBy length ${invitedBy.length}"),
        Text("usernames length ${usernames.length}")

For the two last lines of code i get :"invitedBy length 1" , "usernames length + infinite number"



Solution 1:[1]

You're calling setState inside your build method. That triggers another build, and setState is called again, and so on...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kirill Bubochkin