How can I create a ToggleButton effect?

545

Store the selected item;

enter image description here

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: SafeArea(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int selected;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _Bar(
          onPressed: onPressed,
          selected: selected,
        ),
        Text('selected: $selected'),
      ],
    );
  }

  void onPressed(int index) {
    setState(() {
      selected = selected == index ? null : index;
    });
  }
}

class _Bar extends StatelessWidget {
  const _Bar({
    Key key,
    this.onPressed,
    this.selected,
  }) : super(key: key);

  final void Function(int selectedIndex) onPressed;
  final int selected;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        _button(Icons.select_all, 0),
        _button(Icons.edit, 1),
        _button(Icons.stars, 2),
      ],
    );
  }

  Widget _button(IconData iconData, int index) {
    return GestureDetector(
      onTap: () => onPressed(index),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(7),
          color: selected == index ? Colors.red : Colors.grey,
        ),
        width: 50,
        height: 30,
        child: Icon(iconData),
      ),
    );
  }
}
Share:
545
Aimrah
Author by

Aimrah

Updated on December 24, 2022

Comments

  • Aimrah
    Aimrah over 1 year

    I am currently working on creating a profile which contains three buttons

    buttons.

    I want the button to change its color after it got pressed. Additionally the button should go back to normal after another button is tapped. I tried the ToggleButton widget before but it just does not look like I want it to.

    Is there a way to achieve the same function with the FlatButton?