简体   繁体   中英

Flutter: How to convert a stateful widget to a stateless widget and keep state changes

I want to change a stateful widget to a stateless widget and keep the set states functions available, how can I do it?

Maybe you can do it by cubit with the stateless widgets,like this: https://medium.com/@kidherbert43/flutter-study-cubit-with-stateless-widget-2f4cd941edec

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 .

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,
              ),
            );
          }),
        )
        );
  }
}

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.

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

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