我在Flutter项目中实现了RadioButtons,并且那些RadioButtons的onChanged未被调用。我用TextField和CheckBox尝试了同样的方法,但两者都不起作用
main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Different Widgets",
debugShowCheckedModeBanner: false,
home: _showRadioButton());
}
List<Widget> makeRadios() {
int _selected = 0;
void onChanged(int value) {
setState(() {
_selected = value;
});
}
List<Widget> list = List<Widget>();
for (int i = 0; i < 3; i++) {
list.add(Row(
children: <Widget>[
Text("Radio"),
Radio(
value: i,
groupValue: _selected,
onChanged: (int value) {
onChanged(value);
})
],
));
}
for (int i = 0; i < 3; i++) {
list.add(RadioListTile(
value: i,
groupValue: _selected,
onChanged: (int value) {
onChanged(value);
},
title: Text("title"),
activeColor: Colors.red,
secondary: Icon(Icons.access_alarm),
subtitle: Text("Gender"),
));
}
return list;
}
Widget _showRadioButton() {
return Scaffold(
appBar: AppBar(
title: Text("Hi"),
),
body: Container(
padding: EdgeInsets.all(10.0),
child: Center(
child: Column(
children:
makeRadios()
),
),
),
);
}
我不明白为什么未调用单选按钮的onChanged吗? TextField和复选框的onChanged也不起作用。
答案 0 :(得分:0)
以下解决方案对我有用
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
int _selected = 0;
void onChanged(int value) {
setState((){
_selected = value;
});
print('Value = $value');
}
List<Widget> makeRadios() {
List<Widget> list = new List<Widget>();
for(int i = 0; i < 3; i++) {
list.add( new Row(
children: <Widget>[
new Text('Radio $i'),
new Radio(value: i, groupValue: _selected, onChanged: (int value){onChanged(value);})
],
));
}
for(int i = 0; i < 3; i++) {
list.add(new RadioListTile(
value: i,
title: new Text('Radio $i'),
groupValue: _selected,
onChanged: (int value){onChanged(value);},
activeColor: Colors.red,
secondary: new Icon(Icons.home),
subtitle: new Text('Sub Title here'),
));
}
return list;
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Radio Demo'),
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Center(
child: new Column(
children: makeRadios(),
),
),
),
);
}
}
我仍然感到困惑,为什么问题中提到的解决方案不起作用