Home > Software engineering >  Which should I use, StatelessWidget or StatefulWidget?
Which should I use, StatelessWidget or StatefulWidget?

Time:01-16

I'm using StatelessWidget in my code now. I have TextEditingController in build method of StatelessWidget and I want to add dispose method to dispose it. However, the dispose method is only available in StatefulWidget. Do you suggest me to change StatelessWidget to StatefulWidget?

My code:

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final TextEditingController controller = TextEditingController();

    return Scaffold(
      body: Center(
        child: TextField(controller: controller),
      ),
    );
  }
}

I referred to this question, but it doesn't answer my question, because its question is whether StatelessWidget will does it by itself.

Feel free to leave a comment if you need more information.

Which should I use, StatelessWidget or StatefulWidget? I would appreciate any help. Thank you in advance!

CodePudding user response:

You used the StatefulWidget for your code if you add to dispose method to your TextField

StatelessWidget not support to dispose method. Refer this answer

If you used Android Studio Editor for coding just move your cursor to StatelessWidget and press alt enter and wrap it StatefulWidget

If you used VS Code Editor for coding just move your cursor to StatelessWidget and press ctrl . and wrap it StatefulWidget

Refer more for this question also

CodePudding user response:

You need to use StatefulWidget as the dispose method come inside StatefulWidget. StatelessWidget does not support dispose method.

  • Related