返回

Flutter (十四) 实战 - 处理 Cell 的点击事件和状态变化

IOS

在上一篇文章中,我们已经实现了微信发现界面的效果。但是,此时还存在一个问题:cell 的点击事件如何处理,以及 cell 点击时状态的变化。

1. 了解 Cell 的状态

在 Flutter 中,我们可以通过 StatefulWidget 来创建状态可变的组件,而 StatelessWidget 则创建不可变的组件。Cell 的状态变化通常可以通过 StatefulWidget 来实现。

2. 创建一个 StatefulWidget 来表示 Cell

class Cell extends StatefulWidget {
  final String title;
  final String description;

  const Cell({Key? key, required this.title, required this.description}) : super(key: key);

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

3. 在 _CellState 中定义状态变量

class _CellState extends State<Cell> {
  bool _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _isExpanded = !_isExpanded;
        });
      },
      child: AnimatedContainer(
        duration: Duration(milliseconds: 200),
        height: _isExpanded ? 200.0 : 100.0,
        child: Column(
          children: <Widget>[
            Text(widget.title),
            Text(widget.description),
          ],
        ),
      ),
    );
  }
}

_CellState 中,我们定义了一个名为 _isExpanded 的状态变量,它表示 Cell 是否处于展开状态。当 Cell 被点击时,我们会调用 setState() 方法来改变 _isExpanded 的值,从而实现 Cell 状态的变化。

4. 将 Cell 添加到 ListView 中

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('微信发现'),
      ),
      body: ListView(
        children: <Widget>[
          Cell(title: 'Cell 1', description: 'This is Cell 1.'),
          Cell(title: 'Cell 2', description: 'This is Cell 2.'),
          Cell(title: 'Cell 3', description: 'This is Cell 3.'),
        ],
      ),
    );
  }
}

现在,我们就可以在 ListView 中看到 Cell 了,并且可以点击 Cell 来改变其状态。

5. 总结

在本篇文章中,我们向您展示了如何在 Flutter 中处理 Cell 的点击事件,以及如何在 Cell 被点击时改变其状态。我们使用 ListViewGestureDetectorInkWell 来实现这一功能。