簡體   English   中英

如何使所有過濾器在輕按顫動時不會改變顏色

[英]How do I make it so that all filters don't change color when tapped on flutter

我正在嘗試為過濾器制作一個模板,該模板接受一個參數(標簽名稱)並在點擊時突出顯示。 但問題是當一個過濾器被點擊時,所有過濾器都會改變顏色,因為它們都使用相同的布爾值。 抱歉,我是初學者,我想我的做法是錯誤的

  class _HomeState extends State<Home> {
  bool filterTap = true;
  GestureDetector filterTemplate(String tag) {
    return GestureDetector(
        onTap: () {
        setState(() {
          filterTap = !filterTap;
        });
      },
      child: Center(
        child: Container(
          margin: const EdgeInsets.only(right: 20.0),
          padding: const EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.all(Radius.circular(4.0)),
            color: filterTap ? Colors.grey : Colors.transparent,
          ),
          child: Text(
            tag,
            style: TextStyle(
              color: filterTap ? Colors.grey[900] : Colors.grey,
              letterSpacing: 2.0,
            ),
          ),
        ),
      ),
    );
  }

首先定義一個 StructFilter 類及其屬性,例如這里是一個選項:

class StructFilter  {
  StructFilter(this.tag,this.filterTap);

  String tag;

  bool filterTap;
}

然后將所有過濾器信息收集到 StructFilter 列表中(即List<StructFilter> filterList )。

例如,您可以嘗試:

Listview(
  children: filterList.map((item){
      return filterTemplate(item);
  }).toList();
)

  GestureDetector filterTemplate(StructFilter structFilter) {
    return GestureDetector(
        onTap: () {
        setState(() {
          structFilter.filterTap = !structFilter.filterTap;
        });
       },
      ),
    );
  }

使用ListMapList<YourClass>來維護每個按鈕的狀態。

並嘗試ChoiceChip

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: Home()));
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Map<String, bool> tagsList = {
    "Tag1": false,
    "Tag2": false,
    "Tag3": false,
    "Tag4": false,
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Row(
          children: tagsList.entries.map((entry) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: ChoiceChip(
                label: Text(entry.key),
                selected: entry.value,
                onSelected: (value) {
                  setState(() {
                    tagsList[entry.key] = value;
                  });
                },
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM