I want to change a stateful widget to a stateless widget and keep the set states functions available, how can I do it?
-
1The question sounds like you want to eat the cake and keep it at the same time. Could you clarify your intent? – Robert Sandberg Aug 27 '22 at 16:17
-
there's no way we can change a class type at runtime. Clarify what do you wanna do but the answer is probably simple: if your widget has a state then it's a stateful widget not a stateless, this also sounds like a XY problem. – Alex Rintt Aug 27 '22 at 16:45
5 Answers
Maybe you can do it by cubit with the stateless widgets,like this: https://medium.com/@kidherbert43/flutter-study-cubit-with-stateless-widget-2f4cd941edec

- 16
No, you can't have setState
on Stateless widget.
setState
method comes from State
.
You can use ValueListenableBuilder or you can pass new data through constructor and call setState on parent both UI will get refresh. Also you can use state management property like provider/riverpod/bloc to manage the state.

- 54,221
- 7
- 29
- 56
-
-
StatefulBuilder comes with state class, yes it can be used but what makes different using StateFullWidget? Rebuild the full widget tree. Then StateFullWidget is better than this. where can have fine control using ValueListenableBuilder – Md. Yeasin Sheikh Aug 27 '22 at 16:31
You can use StatefulBuilder
like this:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Color color = Colors.red;
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: StatefulBuilder(builder: (context, innerstate) {
return InkWell(
onTap: () {
innerstate(() {
color = Colors.black;
});
},
child: Container(
color: color,
),
);
}),
)
);
}
}

- 16,619
- 2
- 12
- 23
-
Don't just post random, uncomplete code. What does `customTheme()`, `CheckBox`, deletedNote etc have to do with OPs question? – Robert Sandberg Aug 27 '22 at 16:20
-
@RobertSandberg It was not random code just show the use case of StatefulBuilder, but in order to clear the answer,I provided some better answer. – eamirho3ein Aug 27 '22 at 16:24
-
Yeah I understand the StatefulBuilder, but when adding a lot of junk it ruins the clarity of the answer. Those extra things have nothing to do with it. – Robert Sandberg Aug 27 '22 at 16:30
There is no way to change states in a stateless widget rather than information is inherited. Stateless is not expecting any changes like stateful in runtime. But stateless can change their interface in runtime due to information given before at widget build.

- 29
- 3
You can work with Bloc, Provider, Riverpod and many other State Management solutions.

- 2,922
- 1
- 13
- 23