Flutter问题记录:Don't put any logic in createState

  • 内容
  • 评论
  • 相关

Don't put any logic in createState 这是刚开始学习Flutter的时候遇到的问题,一开始没在意,因为它只是一个警告不是一个错误,虽然并不影响程序运行,但毕竟也是个问题,最关键是这个提示很烦,vscode 就会看见一个标识错误的波浪线。

下面的代码是自己写的一个图片上传组件,作为讲解的例子,具体的逻辑就不放出来了,总之,这段代码一定会出现警告的,因为在 createState 中通过 构造函数 的方式传入信息,这也是刚学习Flutter容易犯的问题,直觉上就得通过 构造函数 传入参数。

解决警告的方式有两种:

第一种就是在 createState 方法上面加上注释【ignore: no_logic_in_create_state】,让编译器忽略这个问题,但毕竟治标不治本,不建议使用。

第二种就是不要使用 构造函数 入参,体现在下面的代码中就是 _CustomImageUploadState 的构造函数没有,imageFile、onChange、maxLength等字段也没有了,想要使用 CustomImageUpload 中的字段,只需要在 _CustomImageUploadState 中使用 widget.field 即可,比如:widget.maxLength。

class CustomImageUpload extends StatefulWidget {
  CustomImageUpload({super.key, required this.onChnage, this.maxLength = 10});
  // 图片文件列表
  List<ImageObj> imageFile = [];
  // 图片列表变动后触发
  ImageUploadFunction onChnage;
  // 图片最大选择数目
  int maxLength;

  @override
  // ignore: no_logic_in_create_state
  State<CustomImageUpload> createState() => _CustomImageUploadState(
      imageFile: imageFile, onChnage: onChnage, maxLength: maxLength);
}

class _CustomImageUploadState extends State<CustomImageUpload> {
  _CustomImageUploadState(
      {required this.imageFile, required this.onChnage, this.maxLength = 10});
  // 用于标识图片的唯一key 自增
  int scopeIndexKey = 0;
  // 图片文件列表
  List<ImageObj> imageFile;
  // 图片列表变动后触发
  ImageUploadFunction onChnage;
  // 图片最大选择数目
  int maxLength;
  @override
  Widget build(BuildContext context) { print(widget.maxLength) }
}

评论

0条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注