how can i place forloop so that i dont get error?

34 Views Asked by At

how can i use forloop to generate values of data variable please help i am a beginner

class Mentions extends StatefulWidget {
      const Mentions({
        Key? key,
        this.width,
        this.height,
        required this.fullname,
        required this.username,
        required this.photourl,
      }) : super(key: key);
    
      final double? width;
      final double? height;
      final List<String> fullname;
      final List<String> username;
      final List<String> photourl;
    
@override
 _MentionsState createState() => _MentionsState();
}
     
class _MentionsState extends State<Mentions> {
  List<Map<String, dynamic>> data = [];
  void data1(
      for(int i = 0; i< widget.fullname.length; i++) {
      data.add({"Full Name": widget.fullname[i], "username": widget.username[i], "photourl" :widget.photourl[i] });
    }
    )
    );
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
2

There are 2 best solutions below

0
pmatatias On

you can place your method inside initState

class _MentionsState extends State<Mentions> {
  List<Map<String, dynamic>> data = [];
  void data1 (){
    for(int i = 0; i< widget.fullname.length; i++) {
      data.add({
         "Full Name": widget.fullname[i], 
         "username": widget.username[i], 
         "photourl" :widget.photourl[i] 
      });
    }
  )
}

 @override
 void initState() {
   super.initState();
    data1();
  }

 @override
 Widget build(BuildContext context) {
   return Container();
  }
}
0
Vladyslav Ulianytskyi On

try this:

class Mentions extends StatefulWidget {
  Mentions({
    required this.fullname,
    required this.username,
    required this.photourl,
    this.width,
    this.height,
    Key? key,
  }) : super(key: key) {
    for (var i = 0; i < fullname.length; i++) {
      users.add({
        'Full Name': fullname[i],
        'username': username[i],
        'photourl': photourl[i]
      });
    }
  }

  final double? width;
  final double? height;
  final List<String> fullname;
  final List<String> username;
  final List<String> photourl;
  late final List<Map<String, dynamic>> users;

  @override
  _MentionsState createState() => _MentionsState();
}

class _MentionsState extends State<Mentions> {...}

then you can just use widget.users in _MentionsState. but you can even not set all this lists in widget constructor, do mapping to users before, and set to widget constructor just one list with users. and do you really need stateful widget instead of stateless?