In a flutter talk made in 2020, rendering and elements were mentioned. I was writing the same codes to learn, but there were errors. What's wrong with the code?
link = https://www.youtube.com/watch?v=PnWxW21vDak&t=564s
import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
class MyCenter extends SingleChildRenderObjectWidget{
MyCenter({Key? key,Widget? child}) : super(key: key,child: child);
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderMyCenter();
}
}
class _RenderMyCenter extends RenderBox with RenderObjectWithChildMixin<RenderBox>{
@override
void performLayout(){
if(child != null){
child!.layout(constraints.loosen(),parentUsesSize: true);
double dx = (constraints.maxWidth - child!.size.width)/2;
double dy = (constraints.maxHeight - child!.size.height)/2;
BoxParentData childParentData = child!.parentData as BoxParentData;
childParentData.offset = Offset(dx,dy);
}else{
size = const Size(0,0);
}
@override
void paint(PaintingContext context,Offset offset){
if(child!= null){
var parentData = child!.parentData as BoxParentData;
context.paintChild(child as RenderObject, offset+parentData.offset);
}
}
}
}
Then I tried to run the above class but it gave an error.
error = [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Cannot hit test a render box that has never been laid out. The hitTest() method was called on this RenderBox: RenderStack#8503f NEEDS-LAYOUT NEEDS-PAINT: creator: Stack ← _FloatingActionButtonTransition ← MediaQuery ← LayoutId-[<_ScaffoldSlot.floatingActionButton>] ← CustomMultiChildLayout ← AnimatedBuilder ← DefaultTextStyle ← AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#f49e3 ink renderer] ← NotificationListener ← PhysicalModel ← AnimatedPhysicalModel ← ⋯ parentData: offset=Offset(0.0, 0.0); id=_ScaffoldSlot.floatingActionButton
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_detay/WidgetRenderElement/render1.dart';
void main(){
runApp(testApp());
}
class testApp extends StatelessWidget {
const testApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: testHome(),
);
}
}
class testHome extends StatefulWidget {
testHome({Key? key}) : super(key: key);
@override
State<testHome> createState() => _testHomeState();
}
class _testHomeState extends State<testHome> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: MyCenter(child: Text("HEYYOO"),),
);
}
}