我需要在單擊時隨機更改按鈕在堆疊中的順序,我該怎么做?
這是一個例子的代碼,堆疊中的 4 個按鈕一個接一個,當您單擊任何按鈕時,我希望它們隨機更改堆疊中的順序。
你能告訴我我該怎么做嗎?
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key,}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Positioned(
height: 700,
width: 700,
child: SizedBox(
child: ElevatedButton(
onPressed: () {
setState(() {
});
}, child: Text('1'),
),
),
),
Positioned(
height: 600,
width: 600,
child: SizedBox(
child: ElevatedButton(
onPressed: () {
setState(() {
});
}, child: Text('2'),
),
),
),
Positioned(
height: 500,
width: 500,
child: SizedBox(
child: ElevatedButton(
onPressed: () {
setState(() {
});
}, child: Text('3'),
),
),
),
Positioned(
height: 400,
width: 400,
child: SizedBox(
child: ElevatedButton(
onPressed: () {
setState(() {
});
}, child: Text('4'),
),
),
),
]
)
);
}
}
uj5u.com熱心網友回復:
將所有按鈕放在一個串列中,并將它們作為子項分配給Stack,當按下任何按鈕時,隨機播放此串列并重建小部件。
class _TestPageState extends State<TestPage> {
late List<Widget> children;
@override
void initState() {
super.initState();
children = [
Positioned(
height: 700,
width: 700,
child: SizedBox(
child: ElevatedButton(
onPressed: onPressed,
child: Text('1'),
),
),
),
Positioned(
height: 600,
width: 600,
child: SizedBox(
child: ElevatedButton(
onPressed: onPressed,
child: Text('2'),
),
),
),
Positioned(
height: 500,
width: 500,
child: SizedBox(
child: ElevatedButton(
onPressed: onPressed,
child: Text('3'),
),
),
),
Positioned(
height: 400,
width: 400,
child: SizedBox(
child: ElevatedButton(
onPressed: onPressed,
child: Text('4'),
),
),
),
];
}
void onPressed() {
setState(() {
children.shuffle();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: children,
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535027.html
標籤:扑镖随机的堆
