如何从无状态小部件(Stateless Widget)转换为有状态小部件(Stateful Widget)?

53

我有一个应用程序屏幕,使用复选框和下拉菜单。然而,我意识到我将其编码为不可变小部件,因此我无法在选择选项时更改状态。如何使它能够工作,以便当选择复选框时,它将显示为“已选中”,而不是空白?

我尝试将代码粘贴到有状态的小部件中,但是一直遇到错误,因为我不完全确定哪些部分应放在哪里。

import 'package:carve_brace_app/model/activity.dart';
import 'package:flutter/material.dart';

class DetailPage extends StatelessWidget {
  final Activity activity;
  DetailPage({Key key, this.activity}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final levelIndicator = Container(
      child: Container(
        child: LinearProgressIndicator(
            backgroundColor: Color.fromRGBO(209, 224, 224, 0.2),
            value: 2.0,
            valueColor: AlwaysStoppedAnimation(Colors.green)),
      ),
    );

    final topContentText = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: 120.0),
        Container(
          width: 90.0,
          child: new Divider(color: Colors.green),
        ),
        SizedBox(height: 10.0),
        Text(
          activity.activityName,
          style: TextStyle(color: Colors.white, fontSize: 45.0),
        ),
        SizedBox(height: 30.0),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Expanded(
                flex: 6,
                child: Padding(
                    padding: EdgeInsets.only(left: 10.0),
                    child: Text(
                      "Last Run: 3-2-19\n"+
                      "Last Avg Strain: 34%\n"+
                      "Last Run Time: 00:45:23",
                      style: TextStyle(color: Colors.white),
                    ))),
            // Expanded(flex: 1, child: newRow)
          ],
        ),
      ],
    );

    final topContent = Stack(
      children: <Widget>[
        Container(
          height: MediaQuery.of(context).size.height * 0.45,
          padding: EdgeInsets.all(40.0),
          width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [
                  Color.fromRGBO(33, 147, 176, 100),
                  Color.fromRGBO(109, 213, 237, 100)
                ],
              ),
            ),
          child: Center(
            child: topContentText,
          ),
        ),
        Positioned(
          left: 235.0,
          top: 180.0,
          child: InkWell(
            onTap: () {
              Navigator.pop(context);
            },
            child: new CircleAvatar(
                radius: 80.0,
                backgroundImage: NetworkImage(activity.icon),
                backgroundColor: Colors.white,
              ),
          ),
        ),
        Positioned(
          left: 8.0,
          top: 60.0,
          child: InkWell(
            onTap: () {
              Navigator.pop(context);
            },
            child: Icon(Icons.arrow_back, color: Colors.white),
          ),
        )
      ],
    );

    final bottomContentText = Text(
      "Config:",
      style: TextStyle(fontSize: 18.0),
    );
    final mappedCheckbox = CheckboxListTile(
     title: Text("Mapped"),
    value: false,
    onChanged: (newValue) { },
    controlAffinity: ListTileControlAffinity.leading,  //  <-- leading Checkbox
    );
    final rtCheckBox = CheckboxListTile(
     title: Text("Real-time Tracking"),
    value: false,
    onChanged: (newValue) { },
    controlAffinity: ListTileControlAffinity.leading,  //  <-- leading Checkbox
    );
    final descriptionText = Text(
      "Description:",
      style: TextStyle(fontSize: 12.0),
    );
    final description = TextFormField(
      decoration: InputDecoration(
      hintText: 'Enter an activity description',
    ),
  );
    final scheduledFor = Text(
      "Scheduled for:",
      style: TextStyle(fontSize: 12.0),
    );
    final dropdown = new DropdownButton<String>(
  items: <String>['Now (Default)', 'B', 'C', 'D'].map((String value) {
    return new DropdownMenuItem<String>(
      value: value,
      child: new Text(value),
    );
  }).toList(),
  hint: Text("Now (Default)"),
  onChanged: (_) {},
);
    final readButton = Container(
        padding: EdgeInsets.symmetric(vertical: 16.0),
        width: 170,//MediaQuery.of(context).size.width,
        child: RaisedButton(
          onPressed: () => {},
          color: Colors.lightBlue,
          child:
              Text("Start", style: TextStyle(color: Colors.white, fontSize: 20)),
        ));
    final bottomContent = Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.all(40.0),
      child: Center(
        child: Column(
          children: <Widget>[bottomContentText, mappedCheckbox, rtCheckBox, descriptionText, description, Text("\n"), scheduledFor, dropdown, readButton],
        ),
      ),
    );

    return Scaffold(
      body: Column(
        children: <Widget>[topContent, bottomContent],
      ),
    );
  }
}

抛出哪种类型的错误? - Mazin Ibrahim
5个回答

151

将鼠标悬停在 StatelessWidget 类上并使用:

Android Studio:

  • Mac: option + enter

  • Windows: alt + enter

Visual Studio Code:

  • Mac: cmd + .

  • Windows: ctrl + .

输入图像描述


输出(您的解决方案):

输入图像描述

这是可用的代码。

class DetailPage extends StatefulWidget {
  final Activity activity;

  DetailPage({Key key, this.activity}) : super(key: key);

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  bool _tracking = false, _mapped = false; // you need this
  String _schedule;

  @override
  Widget build(BuildContext context) {
    final levelIndicator = Container(
      child: Container(
        child: LinearProgressIndicator(backgroundColor: Color.fromRGBO(209, 224, 224, 0.2), value: 2.0, valueColor: AlwaysStoppedAnimation(Colors.green)),
      ),
    );

    final topContentText = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: 120.0),
        Container(
          width: 90.0,
          child: Divider(color: Colors.green),
        ),
        SizedBox(height: 10.0),
        Text(
          widget.activity.activityName,
          style: TextStyle(color: Colors.white, fontSize: 45.0),
        ),
        SizedBox(height: 30.0),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Expanded(
                flex: 6,
                child: Padding(
                    padding: EdgeInsets.only(left: 10.0),
                    child: Text(
                      "Last Run: 3-2-19\n" + "Last Avg Strain: 34%\n" + "Last Run Time: 00:45:23",
                      style: TextStyle(color: Colors.white),
                    ))),
            // Expanded(flex: 1, child: newRow)
          ],
        ),
      ],
    );

    final topContent = Stack(
      children: <Widget>[
        Container(
          height: MediaQuery.of(context).size.height * 0.45,
          padding: EdgeInsets.all(40.0),
          width: MediaQuery.of(context).size.width,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [Color.fromRGBO(33, 147, 176, 100), Color.fromRGBO(109, 213, 237, 100)],
            ),
          ),
          child: Center(
            child: topContentText,
          ),
        ),
        Positioned(
          left: 235.0,
          top: 180.0,
          child: InkWell(
            onTap: () {
              Navigator.pop(context);
            },
            child: CircleAvatar(
              radius: 80.0,
              backgroundColor: Colors.white,
            ),
          ),
        ),
        Positioned(
          left: 8.0,
          top: 60.0,
          child: InkWell(
            onTap: () {
              Navigator.pop(context);
            },
            child: Icon(Icons.arrow_back, color: Colors.white),
          ),
        )
      ],
    );

    final bottomContentText = Text(
      "Config:",
      style: TextStyle(fontSize: 18.0),
    );
    final mappedCheckbox = CheckboxListTile(
      title: Text("Mapped"),
      value: _mapped,
      onChanged: (newValue) => setState(() => _mapped = newValue),
      controlAffinity: ListTileControlAffinity.leading, //  <-- leading Checkbox
    );
    final rtCheckBox = CheckboxListTile(
      title: Text("Real-time Tracking"),
      value: _tracking,
      onChanged: (newValue) => setState(() => _tracking = newValue),
      controlAffinity: ListTileControlAffinity.leading, //  <-- leading Checkbox
    );
    final descriptionText = Text(
      "Description:",
      style: TextStyle(fontSize: 12.0),
    );
    final description = TextFormField(
      decoration: InputDecoration(
        hintText: 'Enter an activity description',
      ),
    );
    final scheduledFor = Text(
      "Scheduled for:",
      style: TextStyle(fontSize: 12.0),
    );
    final dropdown = DropdownButton<String>(
      value: _schedule,
      items: <String>['Now (Default)', 'B', 'C', 'D'].map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      hint: Text("Now (Default)"),
      onChanged: (newValue) {
        setState(() {
          _schedule = newValue;
        });
      },
    );
    final readButton = Container(
        padding: EdgeInsets.symmetric(vertical: 16.0),
        width: 170, //MediaQuery.of(context).size.width,
        child: RaisedButton(
          onPressed: () => {},
          color: Colors.lightBlue,
          child: Text("Start", style: TextStyle(color: Colors.white, fontSize: 20)),
        ));
    final bottomContent = Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.all(40.0),
      child: Center(
        child: Column(
          children: <Widget>[bottomContentText, mappedCheckbox, rtCheckBox, descriptionText, description, Text("\n"), scheduledFor, dropdown, readButton],
        ),
      ),
    );

    return Scaffold(
      body: Column(
        children: <Widget>[topContent, bottomContent],
      ),
    );
  }
}

android studio on mac ? - neobie
@neobie 第一行已经回答了这个问题。我也在 Mac 上使用 Android Studio。 - CopsOnRoad
我从这篇文章中学到的比我实际来这里所学的还要多。如果你想知道,就像我一样,这个操作在Visual Studio Code中被称为“快速修复”。如果你搜索“快速修复”,你会在首选项->键盘快捷键下找到这些键盘组合。不仅这个键盘快捷键可以让你将StatelessWidget转换为StatefulWidget,还有其他上下文操作将出现在其他类上。 - Banjo Batman

6

对于VSCode(Visual Studio Code),在光标位于无状态组件上时使用Ctrl + '.'键可将其转换为有状态组件。


4

你可以使用IntelliJ或VSCode的快捷键,按下Alt+ Enter或选择灯泡图标,当光标在无状态小部件名称上时,然后选择转换为有状态小部件。


0

针对Mac上的Android Studio: 1.将标记放在Stateless widget名称上 2.按下Alt+Enter键 3.选择转换为Stateful widget 4.根据您的要求配置您的Stateful widget


-1

这里提供一个 Android Studio 的解决方案,因为我在这里没有找到一个。

  1. 将标记放在 Stateless widget 名称上:

enter image description here

  1. 按下 Alt+Enter

  2. 选择转换为有状态小部件

  3. 根据您的需求配置您的有状态小部件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接