【问题标题】:pass onTap on parent component in flutter在颤动中传递父组件的onTap
【发布时间】:2022-11-10 00:23:45
【问题描述】:

我正在颤振中制作一个可重用的组件:

可重用组件:

import 'package:flutter/material.dart';

class ReusableCard extends StatefulWidget {
  const ReusableCard({required this.onTap});
  final VoidCallback onTap;

  @override
  State<ReusableCard> createState() => _ReusableCardState();
}

class _ReusableCardState extends State<ReusableCard> {
  @override
  Widget build(BuildContext context) {
    return Card(
        elevation: 50,
        shadowColor: Colors.black,
        color: const Color.fromRGBO(185, 246, 202, 1),
        child: GestureDetector(
          onTap: onTap, <<<---- my onTap function
          child: Row(children: const [
            Text("hello",
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.black,
                )),
          ]),
        ));
  }
}

我在这个 onTap 上遇到错误:Undefined name 'onTap'. Try correcting the name to one that is defined, or defining the name

我想在我的父组件中使用我的 onTap 函数:

body: const Center(
  child: ReusableCard(
    onTap: () {
      print("this is pressed")
    },
  ),
),

这里我在 onTap 上也遇到了错误:A value of type 'Null' can't be assigned to a parameter of type 'void Function()' in a const constructor. Try using a subtype, or removing the keyword 'const'

我是新手,无法弄清楚我做错了什么。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    虽然它是StatefulWidget,但您需要使用widget.VariableName

    onTap: widget.onTap,  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 2014-05-03
      • 2020-05-26
      • 1970-01-01
      相关资源
      最近更新 更多