Home > Software engineering >  How does flutter_riverpod in Flutter convert ConsumerWidget to ConsumerStatefulWidget more convenien
How does flutter_riverpod in Flutter convert ConsumerWidget to ConsumerStatefulWidget more convenien

Time:12-24

I am using flutter_riverpod package.

I want to convert ConsumerWidget to ConsumerStatefulWidget.

However, it took me a lot of time to do it like this:

  1. (code)
class Widget extends ConsumerWidget {
  const Widget({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return …;
  }
}
  1. (remove ref)
class Widget extends ConsumerWidget {
  const Widget({super.key});
  @override
  Widget build(BuildContext context) {
    return …;
  }
}
  1. (change ConsumerWidget to StatelessWidget)
class Widget extends StatelessWidget {
  const Widget({super.key});
  @override
  Widget build(BuildContext context) {
    return …;
  }
}
  1. (converted by the Convert to StatefulWidget action)
class Widget extends StatefulWidget {
  const Widget({super.key});

  @override
  State<Widget> createState() => _WidgetState();
}

class _WidgetState extends State<Widget> {
  @override
  Widget build(BuildContext context) {
    return …;
  }
}
  1. (add Consumer word)
class Widget extends ConsumerStatefulWidget {
  const Widget({super.key});

  @override
  ConsumerState<Widget> createState() => _WidgetState();
}

class _WidgetState extends ConsumerState<Widget> {
  @override
  Widget build(BuildContext context) {
    return …;
  }
}

As you can see, I need to use 5 steps to do it. Is there a faster way?

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

How to convert ConsumerWidget to ConsumerStatefulWidget more easily? I would appreciate any help. Thank you in advance!

CodePudding user response:

If my ConsumerWidget has no parameters,

  • 1. Create a new ConsumerStatefulWidget with the same name.
  • 2a. Copy content of build method of ConsumerWidget to a new created widget.
  • 2b. (If there are other methods in the ConsumerWidget) Copy content of ConsumerWidget to a new created widget. Then remove ref from build.
  • 3. Delete ConsumerWidget.

If my ConsumerWidget has parameters, then I'm doing the same as you, because otherwise I'll have to add a widget. before widget variables.

  • Related