Home > OS >  ChipsChoice with Callback functions - flutter
ChipsChoice with Callback functions - flutter

Time:11-05

I want to create filter list, if user choose each of them do some appropriate stuffs. I found that can be happening with enter image description here

Part of codes for this part:

...
ChipsChoice<int>.single(
      value: tag,
      onChanged: (value) {
        setState(() {
          tag = value;
        });
      },
...

But for doing other stuffs I need to get selected item index, added a callback function to get index, but IDK have any idea to update the value of tag to change the selected item UI:

enter image description here

Codes for this part:

import 'package:flutter/material.dart';
import 'package:flutter_chip_choice/flutter_chip_choice.dart';

class TagChoices extends StatefulWidget {
  const TagChoices(
      {required this.options, required this.itemCallBack, Key? key})
      : super(key: key);
  final List<Enum> options;
  final Function(int?) itemCallBack;

  @override
  _TagChoicesState createState() => _TagChoicesState();
}

class _TagChoicesState extends State<TagChoices> {
  int tag = 0;

  @override
  Widget build(BuildContext context) {
    return ChipsChoice<int>.single(
      value: tag,
      onChanged: widget.itemCallBack,
      choiceItems: C2Choice.listFrom<int, Enum>(
        source: widget.options,
        style: (i, v) {
          return const C2ChoiceStyle(
            borderRadius: BorderRadius.all(Radius.circular(10)),
            showCheckmark: false,
          );
        },
        activeStyle: (i, v) {
          return const C2ChoiceStyle(
            brightness: Brightness.dark,
          );
        },
        value: (i, v) => i,
        label: (i, v) =>
            v.toString().split(".").last.replaceAll("_", " ").toUpperCase(),
      ),
      choiceStyle: const C2ChoiceStyle(
        color: Colors.blueGrey,
        avatarBorderColor: Colors.white,
      ),
      choiceActiveStyle: const C2ChoiceStyle(
        color: Color(0xFFff004d),
      ),
    );
  }
}

CodePudding user response:

I think you can not set tag like that because widget.itemcallback is from another class. But you can declare tag like another parameter:

class TagChoices extends StatefulWidget {
  const TagChoices(
      {required this.options, required this.itemCallBack, Key? key})
      : super(key: key);
  final List<Enum> options;
  int tag; // <-- tag variable
  final Function(int?) itemCallBack;

  @override
  _TagChoicesState createState() => _TagChoicesState();
}

And the callback function can use tag variable:

ChipsChoice<int>.single(
      value: widget.tag,
      onChanged: widget.itemCallBack,
...
)
  • Related