gpt4 book ai didi

flutter - 选择单个 CheckboxListTile 项目会选择多个项目?

转载 作者:行者123 更新时间:2023-12-03 03:31:30 27 4
gpt4 key购买 nike

在下面的代码中,选择“选项 A”也会自动选择“选项 B”。
这段代码基本上是从 CheckboxListTile class documentation example 复制粘贴的,两次。

class Alergias extends StatefulWidget {
@override
_AlergiasState createState() => _AlergiasState();
}

class _AlergiasState extends State<Alergias> {
@override
Widget build(BuildContext context) {
return Scaffold(
...
body: Column(
CheckboxListTile(
title: const Text("Option A"),
value: timeDilation != 1.0,
controlAffinity: ListTileControlAffinity.leading,
onChanged: (bool value) {
setState(() {
timeDilation = value ? 2.0 : 1.0;
});
},
),
CheckboxListTile(
title: const Text("Option B"),
value: timeDilation != 1.0,
controlAffinity: ListTileControlAffinity.leading,
onChanged: (bool value) {
setState(() {
timeDilation = value ? 2.0 : 1.0;
});
},
),
],
),
);
}
}
我不明白为什么会发生这种情况,或者它是否与 StatefulWidget 状态有关。谁能帮我?

最佳答案

问题是由于相同 timeDilation 引起的CheckboxListTile 中使用的变量.
看看下面的代码,

import 'package:flutter/material.dart';

import 'package:flutter/scheduler.dart' show timeDilation;

void main() => runApp(MyApp());

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
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: Center(
child: MyStatefulWidget(),
),
),
);
}
}

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

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

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var value1 = timeDilation.abs();
var value2 = timeDilation.abs();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children : <Widget>[
CheckboxListTile(
title: const Text("Option A"),
value: value1 != 1.0,
controlAffinity: ListTileControlAffinity.leading,
onChanged: (bool value) {
setState(() {
value1 = value ? 2.0 : 1.0;
});
},
),
CheckboxListTile(
title: const Text("Option B"),
value: value2 != 1.0,
controlAffinity: ListTileControlAffinity.leading,
onChanged: (bool value) {
setState(() {
value2 = value ? 2.0 : 1.0;
});
},
),
],
),
);
}
}

关于flutter - 选择单个 CheckboxListTile 项目会选择多个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63663609/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com