Search code examples
flutterstatefulwidgetstatelesswidget

StatelessWidget to StatefulWidget


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

Solution

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