单选按钮未更改Flutter中的选择

ct2axkht  于 2023-01-27  发布在  Flutter
关注(0)|答案(5)|浏览(260)

我正在创建动态单选按钮并设法显示它。但是,当我点击它时,它没有更改选择。我可以看到onchanged事件被激发。我正在获取输出,但我认为SetState没有按预期工作。
下面是代码。

class FruitsList {
  String name;
  int index;
  FruitsList({this.name, this.index});
}

int  _selectedRadioIndex = 1;

// Default Radio Button Item
  String radioItem = 'Mango';
 
  // Group Value for Radio Button.
  int id = 1;
 
  List<FruitsList> fList = [
    FruitsList(
      index: 1,
      name: "Mango",
    ),
    FruitsList(
      index: 2,
      name: "Apple",
    ),
    FruitsList(
      index: 3,
      name: "Banana",
    ),
    FruitsList(
      index: 4,
      name: "Cheery",
    ),
  ];
Column(
              children: 
                fList.map((data) => RadioListTile(
                  title: Text("${data.name}"),
                  groupValue: id,
                  value: data.index,
                  onChanged: (val) {
                    setState(() {
                      radioItem = data.name ;
                      id = data.index;
                      print(id);
                      print(radioItem);
                      print(val);
                      _selectedRadioIndex = val;
                    });
                  }, 
                )).toList(),
            ),

我哪里做错了?

更新

如春虎君所言。
我试过了。

showDialog(
  context: context,
  builder: (context) {
      return StatefulBuilder(
      builder: (context, setState) {
  Column(
              children:            
                fList.map((data) => RadioListTile(
                  title: Text("${data.name}"),
                  groupValue: id,//_selected,//id,
                  value: data.index,
                  onChanged: (val) {
                    setState(() {
                      radioItem = data.name ;
                      id = data.index;
                      print(id);
                      print(radioItem);
                      print(val);
                      _selectedRadioIndex = val;
                    });
                  }, 
                )).toList(),
            );
  }
  );
  },
  );

但是在这些地方它给出了错误。

showDialog(
  context: context,
  builder: (context) {

'showDialog' must have a method body because '_ApointmentPriceState' isn't abstract.
Try making '_ApointmentPriceState' abstract, or adding a body to 'showDialog'.
tf7tbtn2

tf7tbtn21#

你可以复制粘贴运行下面的完整代码
您可以将RowStatefulBuilder Package 在一起,并使用List<int> _selectedRadioIndexListCardNo来控制
代码片段

List<int> _selectedRadioIndexList = [];
int CardNo = -1;
...
_selectedRadioIndexList.add(0);
CardNo = CardNo + 1;
int thisCardNo = CardNo;
... 
_selectedRadioIndexList[thisCardNo] = val;  

StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
            return Row(
              children: fList
                  .map((data) => Container(
                    width: 100,
                    child: RadioListTile(
                          title: Text("${data.name}"),
                          groupValue: id,
                          value: data.index,
                          onChanged: (val) {
                            setState(() {
                              radioItem = data.name;
                              id = data.index;
                              print(id);
                              print(radioItem);
                              print(val);
                              _selectedRadioIndex = val;
                            });
                          },
                        ),
                  ))
                  .toList(),
            );
          })

工作演示

全码

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class FruitsList {
  String name;
  int index;
  FruitsList({this.name, this.index});
}

class Price extends StatefulWidget {
  @override
  _PriceState createState() => _PriceState();
}

class _PriceState extends State<Price> {
  static final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  int currentIndex = 0;
  String person;
  String age;
  String job;

  // Default Radio Button Item
  String radioItem = 'Mango';

  // Group Value for Radio Button.
  int id = 1;
  //int _selectedRadioIndex = 1;
  List<int> _selectedRadioIndexList = [];

  List<FruitsList> fList = [
    FruitsList(
      index: 1,
      name: "Mango",
    ),
    FruitsList(
      index: 2,
      name: "Banana",
    ),
    FruitsList(
      index: 3,
      name: "Apple",
    ),
    FruitsList(
      index: 4,
      name: "Cherry",
    ),
  ];
  int CardNo = -1;
  @override
  void initState() {
    super.initState();
    cards.add(createCard());
  }

  var nameTECs = <TextEditingController>[];
  var ageTECs = <TextEditingController>[];
  var jobTECs = <TextEditingController>[];

  var cards = <Card>[];

  Card createCard() {
    var nameController = TextEditingController();
    var ageController = TextEditingController();
    var jobController = TextEditingController();
    nameTECs.add(nameController);
    ageTECs.add(ageController);
    jobTECs.add(jobController);
    _selectedRadioIndexList.add(0);
    CardNo = CardNo + 1;
    int thisCardNo = CardNo;

    return Card(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text('Service ${cards.length + 1}'),
          TextFormField(
            style: TextStyle(color: Colors.blue),
            controller: nameController,
            decoration: InputDecoration(labelText: 'Name'),
            validator: validatetext,
            onSaved: (String val) {
              person = val;
            },
          ),

          TextFormField(
            style: TextStyle(color: Colors.blue),
            controller: ageController,
            decoration: InputDecoration(labelText: 'age'),
            validator: validatetext,
            onSaved: (String val) {
              age = val;
            },
          ),
          TextFormField(
            style: TextStyle(color: Colors.blue),
            controller: jobController,
            decoration: InputDecoration(labelText: 'Job'),
            validator: validatetext,
            onSaved: (String val) {
              job = val;
            },
          ),

          //Expanded(
          //            child: Container(
          //            height: 350.0,
          //            child:
          StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
            return Row(
              children: fList
                  .map((data) => Container(
                        width: 100,
                        child: RadioListTile(
                          title: Text("${data.name}"),
                          groupValue: id,
                          value: data.index,
                          onChanged: (val) {
                            setState(() {
                              radioItem = data.name;
                              id = data.index;
                              print(id);
                              print(radioItem);
                              print(val);
                              _selectedRadioIndexList[thisCardNo] = val;
                            });
                          },
                        ),
                      ))
                  .toList(),
            );
          }),
          //)),

          /* CheckboxListTile(
        title: Text("title text"),
        value: checkedValue,
        onChanged: (newValue) {
                     setState(() {
                       checkedValue = newValue;
                     });
                   },
        //onChanged: (newValue) { ... },
        controlAffinity: ListTileControlAffinity.leading,  //  <-- leading Checkbox
      ), */

          SizedBox(height: 10),
        ],
      ),

      //   ),
    );
  }

  void _validateInputs() {
    print('button');
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      _onDone();
    } else {}
  }

  _onDone() {
    updateProfile();
    List<PersonEntry> entries = [];
    for (int i = 0; i < cards.length; i++) {
      var name = nameTECs[i].text;
      var age = ageTECs[i].text;
      var job = jobTECs[i].text;
      entries.add(PersonEntry(name, age, job));
    }
  }

  ///////// Save to DB ////////////////////
  Future updateProfile() async {
    try {
      for (int i = 0; i < cards.length; i++) {
        var name = nameTECs[i].text;
        var age = ageTECs[i].text;
        var job = jobTECs[i].text;

        Map<String, dynamic> body = {'name': name, 'age': age, 'job': job};

        print(body);
        nameTECs[i].clear();
        //if(rang == true){

        Response response = await Dio()
            .post("http://192.168.1.102:8080/adddetails.php", data: body);
        print(response.statusCode);
        if (response.statusCode == 404) {
          print('404');
        }
        if (response.statusCode == 200) {
          nameTECs[i].clear();
        }
      }
    } catch (e) {
      print("Exception Caught: $e");
    }
  }

  ///////////////////////////////

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      //appBar: myAppBar(),
      //endDrawer: myDrawer(),
      body: Column(
        children: <Widget>[
          Expanded(
            child: new Form(
              key: _formKey,
              child: ListView.builder(
                itemCount: cards.length,
                itemBuilder: (BuildContext context, int index) {
                  return cards[index];
                },
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 2.0),
            color: Colors.grey,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                //    Container(
                Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: FloatingActionButton(
                      heroTag: "btn1",
                      child: Icon(Icons.add),
                      onPressed: () => setState(() => cards.add(createCard())),
                      backgroundColor: Colors.green,
                    )

                    /*RaisedButton(
                  child: Text('Add new'),
                  onPressed: () => setState(() => cards.add(createCard())),
                ),*/
                    ),
                Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: FloatingActionButton(
                      heroTag: "btn2",
                      child: Icon(Icons.remove),
                      onPressed: () => setState(() => cards.removeLast()),
                      backgroundColor: Colors.red,
                    )),
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: FloatingActionButton(
                      heroTag: "btn3",
                      child: Icon(Icons.save),
                      onPressed: _validateInputs),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class PersonEntry {
  final String name;
  final String age;
  final String studyJob;

  PersonEntry(this.name, this.age, this.studyJob);
  @override
  String toString() {
    return 'Person: name= $name, age= $age, study job= $studyJob';
  }
}

Size get preferredSize => Size.fromHeight(kToolbarHeight);

String validatetext(String value) {
  if (value.length < 5)
    return 'More than 5 char is required';
  else
    return null;
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Price(),
    );
  }
}
pftdvrlh

pftdvrlh2#

import 'package:flutter/material.dart';

    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }

    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
      
    final String title;

  

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

class _MyHomePageState extends State<MyHomePage> {

  var _selectedRadioIndex = 1;

  @override
  Widget build(BuildContext context) {

String radioItem = 'Mango';
int id = 1;

List<FruitsList> fList = [
  FruitsList(
    index: 1,
    name: "Mango",
  ),
  FruitsList(
    index: 2,
    name: "Apple",
  ),
  FruitsList(
    index: 3,
    name: "Banana",
  ),
  FruitsList(
    index: 4,
    name: "Cheery",
  ),
];
return Scaffold(
  appBar: AppBar(
    title: Text(widget.title),
  ),
  body: Center(
    child: Column(
      children:
      fList.map((data) => RadioListTile(
        title: Text("${data.name}"),
        groupValue: _selectedRadioIndex,
        value: data.index,
        onChanged: (val) {
          setState(() {
            _selectedRadioIndex = val;
            radioItem = data.name ;
            id = data.index;
            print(id);
            print(radioItem);
            print(val);

          });
        },
      )).toList(),

    ),
    ),
  
);
  }
}

class FruitsList {
  String name;
  int index;
  FruitsList({this.name, this.index});
}
chhqkbe1

chhqkbe13#

您将组值设置为id,但在setState中更改的是_selectedRadioIndex,请按如下方式更改代码:

RadioListTile(
                  title: Text("${data.name}"),
                  groupValue: _selectedRadioIndex,//_selected,//id,
                  value: data.index,
                  onChanged: (val) {
                    setState(() {
                      radioItem = data.name ;
                      id = data.index;
                      print(id);
                      print(radioItem);
                      print(val);
                      _selectedRadioIndex = val;
                    });
o2rvlv0m

o2rvlv0m4#

我只是遇到了同样的问题,发现所有这些解决方案都很复杂。
我的解决方案是先创建一个空的Map,使用你的无线电设备唯一的键类型,对我来说int就足够了:

Map<int, int> _selectedRadioValue = {};

然后对groupValue使用此值:

groupValue: (_selectedRadioValue[variant.id!] != null) ? _selectedRadioValue[variant.id!] : 1,

设置新值时:

_selectedRadioValue[variant.id!] = value!;

小部件的完整代码:

Wrap(
    alignment: WrapAlignment.start,
    runSpacing: 5,
    spacing: 25,
    children: <Widget>[
        for (Choice choice in variant.choices!)

        RadioListTile<int>(
            title: Text("${choice.name}"),
            value: choice.position!,
            groupValue: (_selectedRadioValue[variant.id!] != null) 
                ? _selectedRadioValue[variant.id!] : 1,
            onChanged: (int? value) {
                setState(() {
                    _selectedRadioValue[variant.id!] = value!;
                });
            },
        ),
    ],
),
ntjbwcob

ntjbwcob5#

如果使用radioGroup微件

int selectedWeekDay=0 ;  //declare parameter: selectedWeekDay as instance variable 
                      //in the class 
                      //monitors the changes to the radio group selection. 
                      //Can be any type. here i use int, represent 0 to 6 
                      //(weekdays)

final _radioOptionsList = [0, 1, 2, 3, 4, 5, 6];  //the list of days.

这里返回小部件...

Widget weeklyRadioButton() {   
return SizedBox(
  height:50,
  width:300,
  child:  RadioGroup<int>.builder( 
            direction: Axis.horizontal,
            groupValue: **selectedWeekDay**,//... default value 
            horizontalAlignment: MainAxisAlignment.spaceAround,
            onChanged: (value) => setState(() {                  
              **selectedWeekDay** = value!;                                  
            }),
            
            items: _radioOptionsList,
            textStyle: const TextStyle(
              fontSize: 8,
              color: Colors.blue,
            ),
            itemBuilder: (item) => RadioButtonBuilder(
              item.toString(),   //...text to show on each radio button
            ),
          ),
   );

}

相关问题