在Flutter中安装flutter_lints后,不要在createState中放置任何逻辑

ryoqjall  于 2022-12-14  发布在  Flutter
关注(0)|答案(2)|浏览(195)

我在我的项目中安装了flutter_lints插件,安装后它会显示一个警告消息“不要在createState中放置任何逻辑”。如何解决这个问题?

class OverviewPage extends StatefulWidget {
  final int id;
  const OverviewPage({Key? key, required this.id}) : super(key: key);

  @override
  _OverviewPageState createState() => _OverviewPageState(id); // Warning on this line
}

class _OverviewPageState extends State<OverviewPage>{
  late final int id;
  _OverviewPageState(this.id);
}
zwghvu4y

zwghvu4y1#

不要在构造函数中向_OverviewPageState传递任何内容。

class OverviewPage extends StatefulWidget {
  final int id;
  const OverviewPage({Key? key, required this.id}) : super(key: key);

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

class _OverviewPageState extends State<OverviewPage>{
  // if you need to reference id, do it by calling widget.id
}
bttbmeg0

bttbmeg02#

如果有人想从主类初始化状态中的变量,你可以使用,例如,因为你不能在构造函数类中使用它。

@override
void initState() {
    super.initState();
    id = widget.id;
    code = widget.code;
    //your code here
}

相关问题