StatelessWidget to StatefulWidget

1,397

Solution 1

You can automatically convert it by pressing a shortcut on your keyboard above StatelessWidget and it should provide you the option to convert to a StatefulWidget.

On Mac try: CMD + .

On Window try: CTRL + .

Anyway, here you have it:

class NavigationControls extends StatefulWidget {
  const NavigationControls(this._webViewControllerFuture)
      : assert(_webViewControllerFuture != null);

  final Future<WebViewController> _webViewControllerFuture;

  @override
  _NavigationControlsState createState() => _NavigationControlsState();


class _NavigationControlsState extends State<NavigationControls> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<WebViewController>(
      future: widget._webViewControllerFuture,
      builder:
          (BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
        final bool webViewReady =
            snapshot.connectionState == ConnectionState.done;
        final WebViewController controller = snapshot.data;
        return _buttonsPagination(webViewReady, controller, context);
      },
    );
  }}

Solution 2

You can just place your cursor on the StatelessWidget, press Alt + Enter and click on Convert to StatefulWidget. All the boilerplate code will be created for you, automatically.

Yay!

enter image description here

Share:
1,397
Alexandre Marques
Author by

Alexandre Marques

Updated on December 17, 2022

Comments

  • Alexandre Marques
    Alexandre Marques over 1 year

    I'm adapting a class from Wikipedia Explorer (open source) to browse pre-selected pages. I'm trying to add a page counter that it doesn't update because it is a StatelessWidget. Can someone help me to turn it into StatefulWidget?

    class NavigationControls extends StatelessWidget {
      const NavigationControls(this._webViewControllerFuture)
          : assert(_webViewControllerFuture != null);
    
      final Future<WebViewController> _webViewControllerFuture;
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder<WebViewController>(
          future: _webViewControllerFuture,
          builder:
              (BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
            final bool webViewReady =
                snapshot.connectionState == ConnectionState.done;
            final WebViewController controller = snapshot.data;
            return _buttonsPagination(webViewReady, controller, context);
          },
        );
      }