sona
sona

Reputation: 1

The toggle button is not working for more than 3 buttons. We have to change anything in this code other than isSelect and icons

The toggle button is not working for more than 3 buttons. We have to change anything in this code other than isSelect and icons.

ToggleButtons(
  children: <Widget>[
    Icon(Icons.ac_unit),
    Icon(Icons.call),
    Icon(Icons.cake),
 ],
  onPressed: (int index) {
    setState(() {
       for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
         if (buttonIndex == index) {
           isSelected[buttonIndex] = !isSelected[buttonIndex];
         } else {
           isSelected[buttonIndex] = false;
         }
       }
     });
  },
  isSelected: isSelected,
),

Upvotes: 0

Views: 939

Answers (1)

bluenile
bluenile

Reputation: 6029

The issue with your code is that isSelected is not properly initialized before being used. example :

List<bool> isSelected = List.generate(3, (index) => false);
//where 3 is the number of icons shown.

Please see working code below :

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  
  List<bool> isSelected = List.generate(6, (index) => false);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ToggleButtons(
          children:  [
    Icon(Icons.ac_unit),
    Icon(Icons.call),
    Icon(Icons.cake),
            Icon(Icons.add),
            Icon(Icons.accessibility),
        Icon(Icons.analytics),
  ],
          onPressed: (int index) {
            setState(() {
              for (int buttonIndex = 0;
                  buttonIndex < isSelected.length;
                  buttonIndex++) {
                if (buttonIndex == index) {
                  isSelected[buttonIndex] = !isSelected[buttonIndex];
                } else {
                  isSelected[buttonIndex] = false;
                }
              }
            });
          },
          isSelected: isSelected,
        ),
      ),
    );
  }
}

Upvotes: 0

Related Questions