I am creating a web with Flutter web and I would like to implement a button that automatically scrolls the view down to a certain widget. For this I am using a scroll controller and a global key
ScrollController _scrollController = ScrollController();
final _key = GlobalKey();
that I assigned to the desired container
Widget contact() {
return Container(
key: _key,
...
);
}
This is my main Scaffold. I am using a CustomScrollView:
return Scaffold(
body: CustomScrollView(
controller: _scrollController,
slivers: [
NavBar(navBarBackground()),
SliverList(
delegate: SliverChildListDelegate(
[
imageAndText(),
highlights(),
androidIosDesktop(),
multiplatform(),
phrase(),
contact(),
const Footer(),
],
),
)
],
),
);
and I am trying to implement this function for the button
void jump() {
_scrollController.position.ensureVisible(
_key.currentContext.findRenderObject(),
alignment: 0.5,
duration: const Duration(seconds: 1),
);
}
but I get an error on _key.currentContext.findRenderObject()
due to null safety.
It says that I should add a null check to the target but I do not know where I should do it. I tried with the key but it does not work there. (I already tried writing ?. but that still gives an error)
Any idea how to solve this error, or maybe how to scroll down to a specific widget in another way? (I already tried jumping to offset but I prefer this approach since I don't have to worry about changing any dimensions).
Thanks in advance.
CodePudding user response:
change it to _key.currentContext!.findRenderObject()!
if you sure it cannot be null