import 'package:flutter/material.dart';
class ButtonRow extends StatefulWidget {
@override
_ButtonRowState createState() => _ButtonRowState();
}
class _ButtonRowState extends State<ButtonRow> {
int _selectedIndex = 0;
List<String> _buttonTitles = ['Button 1', 'Button 2', 'Button 3', 'Button 4'];
@override
Widget build(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: _buttonTitles.length,
itemBuilder: (BuildContext context, int index) {
return Container(
margin: EdgeInsets.all(8.0),
child: ElevatedButton.icon(
onPressed: index == _selectedIndex ? null : () {
setState(() {
_selectedIndex = index;
});
},
icon: Icon(Icons.check),
label: Text(
_buttonTitles[index],
style: TextStyle(
color: index == _selectedIndex ? Colors.white : Colors.black,
),
),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return Colors.grey; // Disabled button color
}
return index == _selectedIndex
? Colors.blue // Selected button color
: null;
},
),
),
),
);
},
);
}
}
In this example, _selectedIndex keeps track of the currently selected button's index. The _buttonTitles list contains the text for each button. The ButtonStyle sets the background color based on the button's state (selected, disabled, or default). The ElevatedButton.icon widget displays an icon and text on each button.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Button Row Demo'),
),
body: Center(
child: ButtonRow(),
),
),
);
}