flutter 如何在拖动时更新可拖动反馈小部件?

9jyewag0  于 2023-03-24  发布在  Flutter
关注(0)|答案(1)|浏览(123)

我想做一个游戏,我需要能够点击一个按钮,而拖动一个小部件,该按钮应该呈现som的变化,用户目前正在拖动的反馈小部件。childWhenDraging更新刚刚好,但反馈小部件不更新在拖动过程中。有没有办法实现这一点?
这是重新创建它的基本示例。

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Draggable Test',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int counter;

  @override
  void initState() {
    this.counter = 0;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Draggable Test'),
      ),
      body: Column(
        children: <Widget>[
          Draggable(
            child: Container(
              color: Colors.red,
              width: 100,
              height: 100,
              child: Text(counter.toString()),
            ),
            feedback: Container(
              color: Colors.red,
              width: 100,
              height: 100,
              child: Text(counter.toString()),
            ),
            childWhenDragging: Container(
              color: Colors.red,
              width: 100,
              height: 100,
              child: Text(counter.toString()),
            ),
          ),
          RaisedButton(
            onPressed: () {
              setState(() {
                counter += 1;
              });
            },
            child: Text("plus"),
          )
        ],
      ),
    );
  }
}

我期望反馈小部件呈现正确的计数器值,但它从不更新。

0lvr5msh

0lvr5msh1#

这种行为是可拖动小部件实际实现的结果。看看flutter/lib/src/widgets/drag_target中的以下行:

_DragAvatar({
    required this.overlayState,
    this.data,
    this.axis,
    required Offset initialPosition,
    this.dragStartPoint = Offset.zero,
    this.feedback,
    this.feedbackOffset = Offset.zero,
    this.onDragUpdate,
    this.onDragEnd,
    required this.ignoringFeedbackSemantics,
    required this.ignoringFeedbackPointer,
  }) : assert(overlayState != null),
       assert(ignoringFeedbackSemantics != null),
       assert(ignoringFeedbackPointer != null),
       assert(dragStartPoint != null),
       assert(feedbackOffset != null),
       _position = initialPosition {
    _entry = OverlayEntry(builder: _build);
    overlayState.insert(_entry!);
    updateDrag(initialPosition);
  }

_entry是显示的feedback小部件。仔细看,你可以看到它实际上是一个叠加!(参见OverlayEntry
因此,当通过setState更新应用的当前状态时,“应用小部件”的上下文会按预期更新。但是反馈小部件所在的Overlay不属于“应用小部件上下文”。
要更新反馈小部件,您可以执行以下操作:
1.使反馈小部件成为独立的StatefulWidget
1.将主要状态更改传递给反馈小部件
根据框架等的不同,可以通过不同的方式传递状态。为了保持简单,下面的示例使用GlobalKey访问反馈小部件。

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late int counter;

  /// GlobalKey to access CountContainer later
  final GlobalKey _counterKey = GlobalKey();

  @override
  void initState() {
    counter = 0;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Draggable Test'),
      ),
      body: Column(
        children: <Widget>[
          Draggable(
            /// Set feedback widget as CountContainer with the GlobalKey
            feedback: CountContainer(
              initialCount: counter,
              key: _counterKey,
            ),
            childWhenDragging: Container(
              color: Colors.red,
              width: 100,
              height: 100,
              child: Text(counter.toString()),
            ),
            child: Container(
              color: Colors.red,
              width: 100,
              height: 100,
              child: Text(counter.toString()),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                counter += 1;
                // pass update to CountContainer
                (_counterKey.currentState as _CountContainerState).updateCount(counter);
              });
            },
            child: Text("plus"),
          )
        ],
      ),
    );
  }
}

class CountContainer extends StatefulWidget
{
  final int initialCount;
  const CountContainer({Key? key, required this.initialCount}) : super(key: key);

  @override
  State<CountContainer> createState() => _CountContainerState();
}

class _CountContainerState extends State<CountContainer>
{
  late int count = widget.initialCount;

  @override
  Widget build(BuildContext context)
  {
    return Container(
      color: Colors.red,
      width: 100,
      height: 100,
      child: Text(count.toString()),
    );
  }

  /// This function gets called by MyHomePage.
  void updateCount(int newCount)
  {
    setState(() {
      count = newCount;
    });
  }
}

这样,状态就被传递给反馈小部件并正确更新。

相关问题