I want to change a stateful widget to a stateless widget and keep the set states functions available, how can I do it?
CodePudding user response:
Maybe you can do it by cubit with the stateless widgets,like this: https://medium.com/@kidherbert43/flutter-study-cubit-with-stateless-widget-2f4cd941edec
CodePudding user response:
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.
More about setState and State
.
CodePudding user response:
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,
),
);
}),
)
);
}
}
CodePudding user response:
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.
CodePudding user response:
You can work with Bloc, Provider, Riverpod and many other State Management solutions.