为什么在颤振中在类之外声明枚举?

时间:2021-07-24 06:29:56

标签: flutter class dart enums

我正在查看有关单选按钮的 flutter 官方文档,并注意到枚举已在类之外声明。为什么我们不能在类内部声明它们,如果可以,在类内部和外部声明它们有什么区别?

这是示例代码:

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

enum SingingCharacter { lafayette, jefferson }


class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}


class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  SingingCharacter? _character = SingingCharacter.lafayette;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ListTile(
          title: const Text('Lafayette'),
          leading: Radio<SingingCharacter>(
            value: SingingCharacter.lafayette,
            groupValue: _character,
            onChanged: (SingingCharacter? value) {
              setState(() {
                _character = value;
              });
            },
          ),
        ),
        ListTile(
          title: const Text('Thomas Jefferson'),
          leading: Radio<SingingCharacter>(
            value: SingingCharacter.jefferson,
            groupValue: _character,
            onChanged: (SingingCharacter? value) {
              setState(() {
                _character = value;
              });
            },
          ),
        ),
      ],
    );
  }
}

谁能解释一下? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:6)

因为枚举是一种特殊的类,与这个 language tour

<块引用>

枚举类型,通常称为枚举或枚举,是一种特殊的类,用于表示固定数量的常量值。

并且你不能在另一个类中创建一个类

此外,您可以为单选按钮使用地图

相关问题