简体   繁体   中英

Flutter refactor structure

I saw somewhere online that when refactoring widgets in Flutter, you should opt for refactoring them as classes rather than methods. So I wonder if having my page structured like this is bad Flutter practice.

And if so, why? Because it looks cleaner this way in my opinion.

class ProfilePage extends StatefulWidget {
  bool isUserProfile;

  ProfilePage(this.isUserProfile, {Key? key}) : super(key: key);

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

///
///Page state class
///
class _ProfilePageState extends State<ProfilePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Stack(
     
        children: [
          _profileBanner(),
          _whiteBackgroundContainer(),
          _profileImage(),
          _userName(),
          _backArrow(),
          _profilePageButtons(),
          _reputationBuble(),
          _friendsAndGamesCounter(),
          _personnalnformationRow(),
          _divider(),
          _biographyTile(),
        ],
      ),
    );
  }

 
}
  1. Refactor into method
Text buildHello() => Text('Hello');
  1. Refactor into widget
class HelloWidget extends StatelessWidget {
  const HelloWidget({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text('Hello');
  }
}

Now refactoring into method might seem tempting here but when buildHello is too big it might rebuild even when nothing inside buildHello was changed. But when it comes to refactoring into widget, we get all the benefits of widget lifecycle so it will rebuild only when something in widget changes. So this prevents unnecessary rebuilds and thus improving the performance. This also offers all the optimizations that Flutter offers for widget class.

source link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM