Skip to content

Instantly share code, notes, and snippets.

@bambinoua
Last active March 28, 2024 12:08
Show Gist options
  • Save bambinoua/be4f234aabd983d4abf17406e43be56f to your computer and use it in GitHub Desktop.
Save bambinoua/be4f234aabd983d4abf17406e43be56f to your computer and use it in GitHub Desktop.
`ToggleButtons` fill color switcher
import 'package:flutter/material.dart';
void main() {
runApp(const MainApp());
}
enum Buttons {
android,
iOS,
}
class MainApp extends StatefulWidget {
const MainApp({super.key});
@override
State<MainApp> createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
late final ValueNotifier<List<bool>> _states;
@override
void dispose() {
_states.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
_states = ValueNotifier(
Buttons.values.map((button) => button.index == 0).toList());
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return MaterialApp(
home: Scaffold(
body: Center(
child: ValueListenableBuilder(
valueListenable: _states,
builder: (context, states, child) {
final selectedIndex = states.indexOf(true);
return ToggleButtons(
isSelected: states,
selectedColor: theme.colorScheme.surface,
fillColor: selectedIndex == 0
? theme.colorScheme.primary
: theme.colorScheme.tertiary,
onPressed: (index) {
_states.value = Buttons.values
.map((button) => button.index == index)
.toList();
},
children: [
...Buttons.values.map((button) => Padding(
padding: const EdgeInsets.all(8.0),
child: Text(button.name),
)),
],
);
},
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment