flutter 我如何放置forloop,这样我就不会出错?

plicqrtu  于 2023-01-27  发布在  Flutter
关注(0)|答案(2)|浏览(106)

我如何使用forloop来生成数据变量的值请帮助我是一个初学者

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

dm7nw8vv1#

可以将方法放在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();
  }
}
eit6fx6z

eit6fx6z2#

试试这个:

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> {...}

那么你可以只在_MentonsState中使用widget.users。但是你甚至可以不在小部件构造器中设置所有这些列表,在之前Map到用户,并且只为小部件构造器设置一个包含用户的列表。你真的需要有状态的小部件而不是无状态的吗?

相关问题