Flutter togglebuttons full width

Flutter ToggleButtons Full Width

To create Flutter ToggleButtons that span the full width, you can make use of the Expanded widget along with the ListView widget.

  
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('ToggleButtons Full Width'),
        ),
        body: Center(
          child: Padding(
            padding: EdgeInsets.all(16.0),
            child: ToggleButtonRow(),
          ),
        ),
      ),
    );
  }
}

class ToggleButtonRow extends StatefulWidget {
  @override
  _ToggleButtonRowState createState() => _ToggleButtonRowState();
}

class _ToggleButtonRowState extends State {
  List _isSelected = [false, false, false];

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity, // Set width to full width
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          Expanded( // Wrap each button with Expanded widget to divide available space evenly
            child: ToggleButtons(
              children: [
                Icon(Icons.home),
                Icon(Icons.chat),
                Icon(Icons.settings),
              ],
              isSelected: _isSelected,
              onPressed: (index) {
                setState(() {
                  _isSelected[index] = !_isSelected[index];
                });
              },
            ),
          ),
        ],
      ),
    );
  }
}
  
  

In the above example, we have a ToggleButtonRow widget containing a Container with a width of double.infinity to span the full width. Inside the Container, we have a ListView with a horizontal scroll direction to display the toggle buttons in a row.

Each toggle button is wrapped with an Expanded widget to divide the available space evenly. This ensures that the buttons span the full width.

The toggle buttons themselves are created using ToggleButtons widget. In this example, we used simple icons for demonstration purposes.

The isSelected property of the ToggleButtons widget is bound to a list of boolean values (_isSelected), which keeps track of the toggled state of each button. The onPressed callback is used to update the state when a button is pressed.

This implementation allows the toggle buttons to span the full width of the screen, making use of the Expanded and ListView widgets.

Leave a comment