0

我想在子类中实现该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 ?

}
4

3 回答 3

0

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

在此处输入图像描述

在 中ParentWidget,我们定义_childKey了 a 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);
  }
}
于 2021-02-27T15:32:06.180 回答
0

在您的ChildClass中,返回一个GestureDetector. 将child属性设置为其余的小部件,然后将 设置onTap为 call methodA。这应该看起来像这样:

class ChildClass extends StatelessWidget {

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

}
于 2021-02-27T15:32:18.900 回答
0

您在问如何检测子类 onTap 并将其传递给 Parent 对吗?

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}
)
  }
}
于 2021-02-27T15:40:49.867 回答