从StatelessWidget到StatefulWidget

时间:2020-01-27 11:16:02

标签: flutter statefulwidget statelesswidget

我正在改编Wikipedia Explorer(开放源代码)中的类以浏览预选页面。我正在尝试添加不会更新的页面计数器,因为它是一个StatelessWidget。有人可以帮我把它变成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);
      },
    );
  }

2 个答案:

答案 0 :(得分:1)

您可以通过按键盘上StatelessWidget上方的快捷方式自动将其转换,并且应该为您提供转换为StatefulWidget的选项。

在Mac上,尝试: CMD +

在Windows上尝试: CTRL +

无论如何,在这里您可以拥有它:

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

答案 1 :(得分:1)

您只需将光标置于StatelessWidget上,按Alt + Enter,然后单击“转换为StatefulWidget”。将自动为您创建所有样板代码。

是的!

enter image description here