rrousselGit / functional_widget

A code generator to write widgets as function without loosing the benefits of classes.
596 stars 46 forks source link

How to mimic class initialization in functional widget #80

Closed Adidi closed 3 years ago

Adidi commented 3 years ago

lets say in some class i need to init something in the constructor:

class _MyPageViewState extends State<MyPageView> {
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }
}

what is the correct way to achive it using functional widget - is this correct:

@hwidget
Widget app(int value) {
  final index = useState(0);
PageController _pageController = PageController(initialPage: 0);
void _onItemTapped(int i) {
    index.value = i;
    _pageController.animateToPage(i,
        duration: Duration(milliseconds: 500), curve: Curves.easeOut);
  }

return Scaffold(); // some widet uses this pageController
}

I know there is usePageController but for the sake of it - what if i need to initialize something ? or write a callback inside the functional widget - is this cause performance issues when build trigger ? Cause in class functions and properties are separate from the build funciton - what is the best practice to do it in functional widget ?

rrousselGit commented 3 years ago

There are numerous hooks with various way to initialize state, like useMemoized, and useEffect