Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

drag and drop - How to update Draggable child when entering DragTarget in Flutter?

I have a number of Draggables and DragTargets. On the Draggables I have specified child and feedback, however I also want it to change it's look when the Draggable enters the DragTarget. I can't see any way to do this.

Whenever I drag the Draggable around, I change it's color to be red, however as soon as it enters the DragTarget I want to update the Draggable color to green.

I am aware of DragTarget.OnWillAccept, this method is called whenever the Draggable enters the DragTarget, but I only have the data. I tried updating the data with new color and then calling setState, but that seemed not to work.

Any suggestions on how to get this behaviour?

I want something like the following callback Draggable.onEnteringDragTarget and Draggable.onLeavingDragTarget.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only way I can think of is using a streambuilder and a stream that will carry the information of whether the draggable is on a drag target. This code provides a basic solution.

class _MyHomePageState extends State<MyHomePage> {
  BehaviorSubject<bool> willAcceptStream;

  @override
  void initState() {
    willAcceptStream = new BehaviorSubject<bool>();
    willAcceptStream.add(false);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          Container(
            height: 400,
            width: double.infinity,
            child: Container(
              width: 100,
              height: 100,
              child: Center(
                child: Draggable(
                  feedback: StreamBuilder(
                    initialData: false,
                    stream: willAcceptStream,
                    builder: (context, snapshot) {
                      return Container(
                        height: 100,
                        width: 100,
                        color: snapshot.data ? Colors.green : Colors.red,
                      );
                    },
                  ),
                  childWhenDragging: Container(),
                  child: Container(
                    height: 100,
                    width: 100,
                    color: this.willAcceptStream.value ?? false
                        ? Colors.green
                        : Colors.blue,
                  ),
                  onDraggableCanceled: (v, f) => setState(
                        () {
                          this.willAcceptStream.add(false);
                        },
                      ),
                ),
              ),
            ),
          ),
          DragTarget(
            builder: (context, list, list2) {
              return Container(
                height: 50,
                width: double.infinity,
                color: Colors.blueGrey,
                child: Center(child: Text('TARGET ZONE'),),
              );
            },
            onWillAccept: (item) {
              debugPrint('will accept');
              this.willAcceptStream.add(true);
              return true;
            },
            onLeave: (item) {
              debugPrint('left the target');
              this.willAcceptStream.add(false);
            },
          ),
        ],
      ),
    );
  }
}

Edit: The first example doesn't handle multiple drags at the same time this on does and it's a little cleaner.

import 'package:rxdart/rxdart.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @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> {
  MyDraggableController<String> draggableController;

  @override
  void initState() {
    this.draggableController = new MyDraggableController<String>();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Draggable Test'),
      ),
      body: Column(
        children: <Widget>[
          Container(
            height: 400,
            width: double.infinity,
            child: Container(
              width: 100,
              height: 100,
              child: Center(
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      left: 30,
                      top: 30,
                      child: MyDraggable<String>(draggableController, 'Test1'),
                    ),
                    Positioned(
                      left: 230,
                      top: 230,
                      child: MyDraggable<String>(draggableController, 'Test2'),
                    )
                  ],
                ),
              ),
            ),
          ),
          DragTarget<String>(
            builder: (context, list, list2) {
              return Container(
                height: 50,
                width: double.infinity,
                color: Colors.blueGrey,
                child: Center(
                  child: Text('TARGET ZONE'),
                ),
              );
            },
            onWillAccept: (item) {
              debugPrint('draggable is on the target');
              this.draggableController.onTarget(true, item);
              return true;
            },
            onLeave: (item) {
              debugPrint('draggable has left the target');
              this.draggableController.onTarget(false, item);
            },
          ),
        ],
      ),
    );
  }
}

class MyDraggable<T> extends StatefulWidget {
  final MyDraggableController<T> controller;
  final T data;
  MyDraggable(this.controller, this.data);
  @override
  _MyDraggableState createState() =>
      _MyDraggableState<T>(this.controller, this.data);
}

class _MyDraggableState<T> extends State<MyDraggable> {
  BehaviorSubject<DraggableInfo<T>> willAcceptStream;
  MyDraggableController<T> controller;
  T data;
  _MyDraggableState(this.controller, this.data);

  @override
  void initState() {
    willAcceptStream = this.controller._isOnTarget;
    willAcceptStream.add(new DraggableInfo<T>(false, this.data));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Draggable<T>(
      data: this.data,
      feedback: StreamBuilder<DraggableInfo<T>>(
        initialData: DraggableInfo<T>(false, this.data),
        stream: willAcceptStream,
        builder: (context, snapshot) {
          return Container(
            height: 100,
            width: 100,
            color: snapshot.data.isOnTarget && snapshot.data.data == this.data ? Colors.green : Colors.red,
          );
        },
      ),
      childWhenDragging: Container(),
      child: Container(
        height: 100,
        width: 100,
        color: (this.willAcceptStream.value.isOnTarget ?? this.willAcceptStream.value.data == this.data)
            ? Colors.green
            : Colors.blue,
      ),
      onDraggableCanceled: (v, f) => setState(
            () {
              this.willAcceptStream.add(DraggableInfo(false, null));
            },
          ),
    );
  }
}

class DraggableInfo<T> {
  bool isOnTarget;
  T data;
  DraggableInfo(this.isOnTarget, this.data);
}

class MyDraggableController<T> {
  BehaviorSubject<DraggableInfo<T>> _isOnTarget;

  MyDraggableController() {
    this._isOnTarget = new BehaviorSubject<DraggableInfo<T>>();
  }

  void onTarget(bool onTarget, T data) {
    _isOnTarget.add(new DraggableInfo(onTarget, data));
  }
}

Edit 2: Solution without using streams and streambuilder. The important part is the feedback widget is stateful.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @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> {
  MyDraggableController<String> draggableController;

  @override
  void initState() {
    this.draggableController = new MyDraggableController<String>();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Draggable Test'),
      ),
      body: Column(
        children: <Widget>[
          Container(
            height: 400,
            width: double.infinity,
            child: Container(
              width: 100,
              height: 100,
              child: Center(
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      left: 30,
                      top: 30,
                      child: MyDraggable<String>(
                        draggableController,
                        'Test1',
                      ),
                    ),
                    Positioned(
                      left: 230,
                      top: 230,
                      child: MyDraggable<String>(
                        draggableController,
                        'Test2',
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          DragTarget<String>(
            builder: (context, list, list2) {
              return Container(
                height: 100,
                width: double.infinity,
                color: Colors.blueGrey,
                child: Center(
                  child: Text('TARGET ZONE'),
                ),
              );
            },
            onWillAccept: (item) {
              debugPrint('draggable is on the target $item');
              this.draggableController.onTarget(true, item);
              return true;
            },
            onLeave: (item) {
              debugPrint('draggable has left the target $item');
              this.draggableController.onTarget(false, item);
            },
          ),
        ],
      ),
    );
  }
}

class MyDraggable<T> extends StatefulWidget {
  final MyDraggableController<T> controller;
  final T data;
  MyDraggable(this.controller, this.data, {Key key}) : super(key: key);
  @override
  _MyDraggableState createState() =>
      _MyDraggableState<T>(this.controller, this.data);
}

class _MyDraggableState<T> extends State<MyDraggable> {
  MyDraggableController<T> controller;
  T data;
  bool isOnTarget;
  _MyDraggableState(this.controller, this.data);
  FeedbackController feedbackController;
  @override
  void initState() {
    feedbackController = new FeedbackController();

    this.controller.subscribeToOnTargetCallback(onTargetCallbackHandler);

    super.initState();
  }

  void onTargetCallbackHandler(bool t, T data) {
    this.isOnTarget = t && data == this.data;
    this.feedbackController.updateFeedback(this.isOnTarget);
  }

  @override
  void dispose() {
    this.controller.unSubscribeFromOnTargetCallback(onTargetCallbackHandler);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Draggable<T>(
      data: this.data,
      feedback: FeedbackWidget(feedbackController),
      childWhenDragging: Container(
        height: 100,
        width: 100,
        color: Colors.blue[50],
      ),
      child: Container(
        height: 100,
        width: 100,
        color: (this.isOnTarget ?? false) ? Colors.green : Colors.blue,
      ),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...