I am currently having an issue with a lazy loading.
I have multiple Items in a PageView and I want to keep track of a widget in the PageView . So I can change the color of it, depending on where it is on the screen.
But the moment the widget leaves the screen I get this issue:
The method 'findRenderObject' was called on null.
Receiver: null
Tried calling: findRenderObject()
I hope someone can help me with this. I think it is because of flutters lazy loading, I thought I is only enabled in listview.builder, but it seems that I was wrong.
Here some code, for you to see what I am doing:
PageController:
final _controller = PageController(
initialPage: 0,
viewportFraction: 0.25,
);
PageView:
PageView(
controller: _controller,
scrollDirection: Axis.vertical,
onPageChanged: (int) {
setState(() {});
},
children: [
_container(width, key1,the_times[0]), // i want to keep track of this widget
_container(width, key2,the_times[1]),
_container(width, key3,the_times[2]),
_container(width, key4,the_times[3]),
_container(width, key5,the_times[4]),
_container(width, key6,the_times[5]),
_container(width, key7,the_times[6]),
_container(width, key8,the_times[7]),
_container(width, key9,the_times[8]),
_container(width, key10,the_times[9]),
_container(width, key11,the_times[10]),
_container(width, key12,the_times[11]),
_container(width, key13,the_times[12]),
],
),
How i find the widget:
Color color_function(GlobalKey key) {
RenderBox box = key1.currentContext.findRenderObject();
Offset position = box.localToGlobal(Offset.zero);
double y = position.dy;
if (y > 160 && y < 240) {
return Colors.white;
} else {
Colors.black;
} }
Finally, the code of the widgets that are being presented on the screen:
Widget _container(double width, GlobalKey key, String title) {
return Container(
key: key,
height: 100,
width: width,
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: AutoSizeText(
title,
style: GoogleFonts.montserrat(
color: second_time == true ? color_function(key) : Colors.white,
),
),
),
);}
I use second_time == true ? to avoid the error message when I start my app, it is false in default, and when all widgets are build it is being changed to true.
But like I said, I run into the error described above, when the widget with key1 is leaving the screen, everything works fine until then.