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);
}
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With