Description
Is your feature request related to a problem? Please describe.
Flutter widget is base on class extends. this Widget System is not match with hooks. SwiftUI and Compose, by contrast, have completely discarded class. their hooks no sense of violation. https://github.com/ra1028/swiftui-hooks
https://github.com/junerver/ComposeHooks
Trying to shoehorn hooks into an class inherited Widget is awkward and doesn't work well. Classes provide their own clear lifecycle, such as initState and dispose, and adding hooks on top only creates a tangled mess, driving up development costs. Users will find it very confusing.
Hooks work best when used in functions; we should completely move away from inheritance.
Describe the solution you'd like
this is a Compose-Style, only use method to define widget instead of class
Widget TestWidget({int initValue = 0}) {
return HookBuilder(
builder: (BuildContext context) {
final c = useState(initValue);
// equals State.didUpdate
if(c.value != initValue){
// trigger rebuild
c.value = initValue;
}
useEffect(() {
print("TestWidget useEffect");
return () {
print("TestWidget dispose");
};
}, []);
return GestureDetector(
onTap: () {
c.value++;
},
child: Container(
child: Column(
children: [
Text("TestWidget"),
Text("c: ${c.value}"),
],
),
),
);
},
);
}
///Class-Widget just as A Wrapper when necessary. example: when you need a route page.
@RoutePage()
class TestWidgetPage extends StatelessWidget {
const TestWidgetPage({super.key});
@override
Widget build(BuildContext context) {
return TestWidget();
}
}
Maybe we can expose HookBuilder only. force user write method-widget.
in #441, The real reason is just that he's using hooks in a class, which is causing some confusion. he changed controller, but the widget not rebuilding, if he use method-widget. he must define controller like this. Because method-widgets require useState for controllers, controller changes will always cause a rebuild.
Widget PageViewPage({Key? key}) {
return HookBuilder(
key: key,
builder: (context) {
final pageController = useState(PageController());
return PageView(
controller: pageController.value,
// ...
);
;
},
);
}