Home > Mobile >  how can i place forloop so that i dont get error?
how can i place forloop so that i dont get error?

Time:01-24

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();
      }
    }

CodePudding user response:

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();
  }
}

CodePudding user response:

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();
}

then you can use widget.users. 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?

  • Related