skip to Main Content

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

Answers


  1. 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();
      }
    }
    
    Login or Signup to reply.
  2. 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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search