【问题标题】:How to pass onTap Function to ListTile in Flutter?Flutter中如何将onTap函数传递给ListTile?
【发布时间】:2021-08-18 12:45:40
【问题描述】:

我的抽屉内容:

drawer: Drawer(
    elevation: 0.0,
    child: Container(
      color: kBackgroundColor,
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            decoration: BoxDecoration(
              color: Colors.grey,
              image: DecorationImage(
                alignment: Alignment.topRight,
                image: AssetImage('images/banner.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: Text('App Test'),
          ),
          ReusableOptionTile(
            textData: 'Home',
            icon: Icons.home,
            onTouch: () {
              print('Home Clicked');
              Navigator.pop(context);
            },
          ),
        ]
      ),
    ),
),

提取的列表磁贴内容:

    class ReusableOptionTile extends StatelessWidget {
 const ReusableOptionTile(
      {required this.icon, required this.textData, required this.onTouch});
  final IconData icon;
  final String textData;
  final Function onTouch;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Row(
        children: [
          Icon(icon),
          SizedBox(
            width: 5.0,
          ),
          Text('$textData'),
        ],
      ),
    onTap: onTouch,   // ERROR POINT
    );
  }
}

我从 Drawer 中提取了 List Tile 以使代码更具可重用性,但现在无法为不同的 tile 传递 on tap 函数。 在错误点显示错误“参数类型'Function'不能分配给参数类型'void Function()?'。”

如何解决这个问题?

【问题讨论】:

  • 您是否尝试将 onTouch 的类型更改为 'void Function()?'?
  • 感谢 Arun,但现在出现错误“主体可能正常完成,导致返回 'null',但返回类型可能是不可为空的类型。尝试添加返回或抛出最后声明。”在这张卡的调用点(从抽屉里)。
  • 你必须在 ReusableOptionTile 中调用 onTouch。 onTap: onTouch()。检查 Len_X 的完整结构的答案。

标签: android flutter dart visual-studio-code flutter-layout


【解决方案1】:

onTouch 应提取为 void 函数

void onTouch(){
 print('Home Clicked');
 Navigator.pop(context);
}

然后

ReusableOptionTile(
            textData: 'Home',
            icon: Icons.home,
            onTouch: onTouch,
          ),

被叫

ListTile(
      title: Row(
        children: [
          Icon(icon),
          SizedBox(
            width: 5.0,
          ),
          Text('$textData'),
        ],
      ),
    onTap: onTouch(),
    );

【讨论】:

    猜你喜欢
    • 2019-08-17
    • 2021-04-07
    • 2019-06-30
    • 1970-01-01
    • 2021-07-21
    • 2021-02-10
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多