如何在 child class 中实现手势检测 - On Tap 方法?

How to implement Gesture detection - On Tap method in child class?

我想在 child class 中实现 GestureDetector 方法 onTap。有没有办法在 Flutter 中做到这一点?

ParentClass.dart

Class ParentClass extends StatelessWidget {

  @override
  Widget build(BuildContext context) { 
     return GestureDetector {
          onTap: methodA,
          child: ChildClass(),
          }

}

ChildClass.dart

Class ChildClass extends StatefulWidget {
   methodA() // need to access methodA which is being passed to gesture detector
   // How do I access methodA of parent class method here
   // so whenever GestureDetector's onTap method is called, i want to handle that in ChildClass is there a way to do it ?

}

您可以使用唯一键访问子状态方法。这是一个最小的例子:

ParentWidget 中,我们定义 _childKey,一个 GlobalKey<_ChildWidgetState> 然后我们可以使用它来访问 State 的方法 updateValue,如下所示:

_childKey.currentState.updateValue('Goodbye, Thierry!'),

完整源代码

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: ParentWidget()),
    );
  }
}

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  final _childKey = GlobalKey<_ChildWidgetState>();

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _childKey.currentState.updateValue('Goodbye, Thierry!'),
      child: ChildWidget(key: _childKey),
    );
  }
}

class ChildWidget extends StatefulWidget {
  const ChildWidget({Key key}) : super(key: key);
  @override
  _ChildWidgetState createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  String value = 'Hello, Thierry!';

  void updateValue(String newValue) {
    setState(() => value = newValue);
  }

  @override
  Widget build(BuildContext context) {
    return Text(value);
  }
}

在你的ChildClass,return一个GestureDetector。将 child 属性 设置为您的其余小部件,然后将 onTap 设置为调用 methodA。那应该看起来像这样:

class ChildClass extends StatelessWidget {

  @override
  Widget build(BuildContext context) { 
     return GestureDetector {
          onTap: methodA,
          child: SomeWidget(),
     }

}

你问的是如何检测子 class onTap 并将其传递给父对吗?

class YourChild extends StatelessWidget {
  final Function parentCallback;

  const YourChild({this.parentCallback}); 

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // 1st option
      onTap: () {
        print("do something");
        parentCallback();
      },
          )
  }
}

然后使用它。

class YourParent extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    return YourChild( parentCallback(){
//do your stuff}
)
  }
}