如何从子状态小部件返回索引单选按钮值到Flutter中的另一个状态小部件



我需要将两个单选按钮的索引值从子状态小部件传递到同一页面中的另一个有状态小部件。然后当value返回时,使用buttonCalculate,我将在"multiply"或";divide"操作。我已经设置了if语句,但我无法从单选按钮获得值。单选按钮是从主状态类MyStatefulWidget()中调用的自定义按钮。

代码如下所示

class calculator extends StatefulWidget {
const calculator({Key? key}) : super(key: key);
@override
State<calculator> createState() => _calculatorState();
}
class _calculatorState extends State<calculator> {
return Scaffold(
appBar: AppBar(... some code here....)

ElevatedButton(onPressed: (){
_showModalBottomSheet(context);
}, child: Text('Calculate'.toUpperCase(),style: TextStyle(fontWeight: FontWeight.bold),), 
),
],
),
);
}
_showModalBottomSheet(context) {
showModalBottomSheet(context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (BuildContext context){
return Container(
child:
MyStatefulWidget(),
),
ElevatedButton(onPressed: (){
if (value == 1){
multiply();
Navigator.of(context).pop();
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => result()));
}else if (value ==2){
divide();
Navigator.of(context).pop();
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => result()));
};
}, child: Text('Calculate'.toUpperCase(),style: TextStyle(fontWeight: FontWeight.bold),),
style: ElevatedButton.styleFrom(
primary: Colors.green),
),
],

我的MyStatefulWidget()类:

class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int value = 0;
Widget CustomRadioButton(String text, int index) {
return OutlinedButton(
onPressed: () {
setState(() {
value = index;
});
},
style: OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
primary: Colors.white,
backgroundColor: (value == index)?Colors.deepOrange: Colors.white,
),
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
CustomRadioButton("Multiply", 1),
CustomRadioButton("Divide", 2),
],
);
}
}

您可以将回调函数传递给MyStatefulWidget,并在单选按钮按下时使用索引值调用该函数。

class MyStatefulWidget extends StatefulWidget {
final Function(int)? onChanged;
const MyStatefulWidget({
Key? key,
this.onChanged,
}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

和按钮的onPressed,你可以用索引值

调用这个函数
onPressed: () {
widget.onChanged?.call(index);
setState(() {
value = index;
});
}

最后,将函数传递给MyStatefulWidget中的onChanged

return Container(child: MyStatefulWidget(onChanged: (value) {
// Now you can use this value
}),
)

相关内容

  • 没有找到相关文章

最新更新