首页 > 解决方案 > Flutter OnSelected - how to access "this"

问题描述

I need to know how to access "this" when using the onSelected function within my button.

Using latest flutter I have the following code:

                        FilterChip(
                          backgroundColor: _colorNavFilter,
                          padding: EdgeInsets.only(
                              top: 8, right: 4, bottom: 8, left: 12),
                          elevation: 2,
                          avatar: CircleAvatar(
                            backgroundColor: Colors.transparent,
                            child: _filter[index]['icon'],
                          ),
                          label: Text(
                            _filter[index]['title'],
                            style: TextStyle(color: _colorNav),
                          ),
                          onSelected: (bool value) {
                            setState(() {
                              if (postCategory == 'false') {
                                postCategory = _filter[index]['title'];
                                _colorNav = Colors.black; // This will end up coloring all buttons in the list - but I want only this specific one 
                                _colorNavFilter = Colors.black;
                              } else {
                                postCategory = 'false';
                                _colorNav = _colorBlue;
                                _colorNavFilter = Colors.white;
                              }
                            });
                          },
                        );

The problem is that it will color all buttons having that variable in black. I'm aware I could define a dedicated variable for every button and then modify this one with index but that seems rather ugly. Can I not do something like "this.color = Colors.black"?

标签: flutterdartthis

解决方案


onSelected是正确的,但您应该将它与selected. 尝试这个:

bool selectedValue = false;

FilterChip(
  backgroundColor: selectedValue? Colors.black : Colors.white,
  selected: selectedValue, // This is important
  padding: EdgeInsets.only(
  top: 8, right: 4, bottom: 8, left: 12),
  elevation: 2,
  avatar: CircleAvatar(
    backgroundColor: Colors.transparent,
    child: _filter[index]['icon'],
    ),
  label: Text(
    _filter[index]['title'],
    style: TextStyle(color: selectedValue? Colors.black : _colorBlue),
  ),
  onSelected: (bool value) {
    setState(() {
      if (postCategory == 'false') {
        postCategory = _filter[index]['title'];
        selectedValue = true;
      } else {
        postCategory = 'false';
        selectedValue = false;
      }
    });
  },
);

推荐阅读