08.Cell点击跳转

前言

在 iOS 开发中,TableView 的 cell 的点击事件是通过代理处理的。那么在 Flutter 中,我们又该怎么处理呢?

首先我们看看点击事件一般是怎样处理的。

点击事件

这里我们可以使用 GestureDetector widget 来包装需要处理点击事件的 widget 。

事件回调 onTap 本质是一个无参数的函数。

/// A tap with a primary button has occurred.
///
/// This triggers when the tap gesture wins. If the tap gesture did not win,
/// [onTapCancel] is called instead.
///
/// See also:
///
///  * [kPrimaryButton], the button this callback responds to.
///  * [onTapUp], which is called at the same time but includes details
///    regarding the pointer position.
final GestureTapCallback? onTap;

/// Signature for when a tap has occurred.
///
/// See also:
///
///  * [GestureDetector.onTap], which matches this signature.
///  * [TapGestureRecognizer], which uses this signature in one of its callbacks.
typedef GestureTapCallback = void Function();

这样我们就可以通过为 Cell 添加一个回调类型的成员,来传入事件。

class MomentHomeCell extends StatelessWidget {
  final String title;
  final String? subTitle;
  final String imageName;
  final String? subImageName;
  final GestureTapCallback? didSelected;

  MomentHomeCell(
      {required this.title,
      this.subTitle,
      required this.imageName,
      this.subImageName,
      this.didSelected});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: didSelected,
      child: ...,
    );
  }
}

使用的地方就可以直接传入事件了:

MomentHomeCell(
              title: '朋友圈',
              imageName: 'images/朋友圈.png',
              didSelected: () {
                print('111');
              },
            ),

页面跳转 Navigator

在 iOS 中我们都是通过 NavigationController 来进行页面跳转的。在 Flutter 中就要用到 Navigator 这个 widget 来进行处理了。

class _MommentPageState extends State<MommentPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        ...
      ),
      body: Container(
        color: Colors.brown,
        child: ListView(
          children: <Widget>[
            MomentHomeCell(
              title: '朋友圈',
              imageName: 'images/朋友圈.png',
              didSelected: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                      builder: (BuildContext context) => MomentDetailPage(title: '朋友圈',),
                  )
                );
              },
            ),
            ...
          ],
        ),
      ),
    );
  }
}

Last updated