Flutter - 展开图标无法正常工作

Flutter - The Expand Icon is not working properly

提问人:Divya 提问时间:3/25/2023 更新时间:3/25/2023 访问量:136

问:

我正在创建可扩展的数据。我尝试使用“展开”图标小部件。但是展开图标无法正常工作。按钮状态未更改。

法典:

  bool _isExpanded = true;
Container(
                color: const Color(0xffeaeaea),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        child: Text('Description'),
                      ),
                      ExpandIcon(
                          expandedColor: Colors.black,
                          color: Colors.black,
                          isExpanded: _isExpanded,
                          onPressed: (bool _isExpanded) {
                            setState(() {
                              _isExpanded = !_isExpanded;
                            });
                          }),
                    ]),
              ),
            if (_isExpanded) const Text('Data'),
Flutter 飞镖 可扩展

评论


答:

1赞 Tushar Patel 3/25/2023 #1

代码中的问题是您在 onPressed 方法的回调中使用了私有 bool 变量,这导致了问题。

以下是工作代码:

class Entry extends StatefulWidget {
  const Entry({Key? key}) : super(key: key);

  @override
  State<Entry> createState() => _EntryState();
}

class _EntryState extends State<Entry> {
  bool _isExpanded = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            color: const Color(0xffeaeaea),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    child: Text('Description'),
                  ),
                  ExpandIcon(
                    isExpanded: _isExpanded,
                    color: Colors.white,
                    expandedColor: Colors.black,
                    disabledColor: Colors.grey,
                    onPressed: (bool isExpanded) {
                      setState(() {
                        _isExpanded = !isExpanded;
                      });
                    },
                  ),
                ]),
          ),
          if (_isExpanded) const Text('Data'),
        ],
      ),
    ));
  }
}