Flutter 通过ToggleButtons实现一组切换按钮。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<bool> _selections = List.generate(3, (index) => false);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: 200,
width: 300,
child: Center(
child: ToggleButtons(
children: [
Icon(Icons.cake),
Icon(Icons.fastfood),
Icon(Icons.local_cafe),
],
isSelected: _selections,
onPressed: (index) {
setState(() {
_selections[index] = !_selections[index];
});
},
color: Colors.green,
selectedColor: Colors.orange,
fillColor: Colors.red,
),
),
),
);
}
}