Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't put any logic in createState after installing flutter_lints in Flutter

Tags:

flutter

dart

I installed flutter_lints plugin in my project, after installing then it shows a warning message "Don't put any logic in createState". How to solve this issue?

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);
}
like image 863
Mohammed Nabil Avatar asked Sep 03 '25 06:09

Mohammed Nabil


2 Answers

Don't pass anything to _OverviewPageState in the constructor.

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
}
like image 128
mmcdon20 Avatar answered Sep 04 '25 18:09

mmcdon20


I guess it'd be better to merge the two answers that you already received.

@mmcdon20 is right, you don't have to pass any argument to the state constructor because, as @Mohamed stated, you can do that via the init_state() using the widget argument or in the _OverviewPageState's constructor.

(I am just doing the fusion of the answers here to be more precise for the ones who are new to Flutter)

The final result should look like this:

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>{
  late int idCopy; 
  // the 'late' keyword is necessary because otherwise Flutter would expect
  // an initialization of the value from a Constructor that accept 'int id' 
  // as a parameter which is what we are trying to avoid because it's not the
  // correct path to follow when you initialize a State of StatefulWidget

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

Hope it clarify doubts for the newcomers :)

Credits: @Mohamed_Hammane, @mmcdon20

like image 28
AndreP Avatar answered Sep 04 '25 18:09

AndreP