When creating a stateless widget, the constructor is const
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: ListView(
),
);
}
}
If I add a ScrollController(), then it is not a const anymore
class MyWidget extends StatelessWidget {
final ScrollController _scrollController = ScrollController();
MyWidget({super.key});
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
controller: _scrollController,
child: ListView(
controller: _scrollController,
),
);
}
}
Does it has an important impact on performances, as it is still a stateless widget. const in general really increase performances as it creates a blueprint that can be reused. Do I have a better solution performance-wise for my widget with ScrollController ?
Thank you
2
Answers
Adding as a required argument does not change anything because it will required to ba called as not a const
If you are that concerned over the
const
keyword, you can "lift up state".Meaning, refactor the code to pass the
controller
one widget to another:And pass it to the child: