Make Stateful Widget inside a Stateless Class

729

No, you can't, a stateless widget is an immutable widget that cannot react to state changes and rerender, you will have to use some form of state management.

If your button and your text and your data are all within the same widget, then it is better to make your widget Stateful and use setState(() {}) to change your text and rerender.

You can use the Flutter plugin in order to convert your widget from a Stateless widget to a StatefulWidget, the plugin will handle everything.

Share:
729
Janis
Author by

Janis

Updated on December 31, 2022

Comments

  • Janis
    Janis over 1 year

    Is it possible to make a Text Widget Stateful so that the Text can be changed when i press a Button without having my Class to be Stateful? example:

    class Rangliste extends StatelessWidget{.... Text(Test), Text(Test2)....}
    

    Test and Test2 are Strings.

    So when i press a Button the values inside the Text Widgets should change. Is there any Way to achieve this without changing my Class to Stateful? Or if not can somebody explain how i can change the Class to Stateful without messing up the rest of my Code

    • Yeasin Sheikh
      Yeasin Sheikh over 2 years
      well i prefer statemanagement in this case,
  • Jimenez
    Jimenez over 2 years
    How about ValueNotifier? We can change value even if it is Stateless widget using ValueNotifier or ChangeNotifier
  • Hamza Mogni
    Hamza Mogni over 2 years
    Yes, we can use that and set up a ValueListenableBuilder to listen for changes. Though I think using Stateful widget, in this case, is the simplest.
  • Janis
    Janis over 2 years
    i did it like in the Orignial answer. Worked out pretty good for me thank you :)