使用堆栈中拖动的小部件更新所有附加的小部件

时间:2019-12-26 10:28:28

标签: flutter draggable

请考虑如图所示的一堆小部件。我们可以看到索引0小部件附加了索引1、2、3、4小部件; ...;索引3小部件附有索引4小部件,而索引4小部件未附有任何人。

stack of widgets
现在,当我拖动一个小部件时,所有附加的小部件也应与其一起拖动
即,如果我尝试拖动索引2小部件,则拖动的小部件应为索引2、3、4小部件的堆栈。
如果我尝试拖动索引4小部件,则被拖动的部件应仅为索引4小部件。

现在,我知道我可以使用 Draggable 类的 feedback childWhenDragging 参数来处理拖动的小部件的更新,但是我不知道知道如何使用它更新所有其他附加的小部件。

这是我的代码:

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: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<BlockWidget> blockWidgets;
  final List<Color> widgetColors = [Colors.red, Colors.brown, Colors.black, Colors.pink, Colors.grey];

  @override
  void initState() {
    super.initState();

    blockWidgets = new List();
    for(int i=0; i < widgetColors.length; i++) {
      blockWidgets.add(BlockWidget(widgetId: i, widgetColor: widgetColors.elementAt(i)));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('AppBar'),
      ),
      body: WidgetStacks(
        blocks: blockWidgets,
      ),
    );
  }
}


const blockHeight = 100.0;
const blockWidth = 100.0;

class BlockWidget {
  int widgetId;
  Color widgetColor;

  BlockWidget({
    @required this.widgetId,
    @required this.widgetColor,
  });
}


class TransformedWidget extends StatefulWidget {
  final BlockWidget block;
  final int stackIndex;
  final List<BlockWidget> attachedBlocks;

  TransformedWidget(
      {@required this.block,
        @required this.stackIndex,
        @ required this.attachedBlocks,
      });

  @override
  _TransformedWidgetState createState() => _TransformedWidgetState();
}

class _TransformedWidgetState extends State<TransformedWidget> {
  @override
  Widget build(BuildContext context) {
    return Transform(
      transform: Matrix4.identity()
        ..translate(
          widget.stackIndex * (blockHeight / 2),
          widget.stackIndex * (blockWidth / 2),
          0.0,
        ),
      child: Draggable<Map>(
        child: _buildBlock(),
        feedback: WidgetStacks(
          blocks: widget.attachedBlocks,
        ),
        childWhenDragging: Container(),
      ),
    );
  }

  Widget _buildBlock() {
    return Container(
      height: blockHeight,
      width: blockWidth,
      color: widget.block.widgetColor,
      alignment: Alignment.centerLeft,
      child: Text(
        widget.block.widgetId.toString(),
        style: TextStyle(
          fontSize: 30.0,
          color: Colors.white,
        ),
      ),
    );
  }
}


class WidgetStacks extends StatefulWidget {
  final List<BlockWidget> blocks;

  WidgetStacks({@required this.blocks});

  @override
  _WidgetStacksState createState() => _WidgetStacksState();
}

class _WidgetStacksState extends State<WidgetStacks> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 5 * blockHeight,
      width: 5 * blockWidth,
      margin: EdgeInsets.all(2.0),
      child: Stack(
        children: widget.blocks.map((block) {
          int index = widget.blocks.indexOf(block);
          return TransformedWidget(
            block: block,
            stackIndex: index,
            attachedBlocks: widget.blocks.sublist(index),
          );
        }).toList(),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

  1. 您应将回调(onDragStart,onDragEnd)传递给您的TransformedWidget,以获取有关拖动事件的通知。
  2. 基于回调,您应该重新构建您的父窗口小部件,以您的情况为WidgetStacks。

以下是工作代码供您参考:

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: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<BlockWidget> blockWidgets;
  final List<Color> widgetColors = [
    Colors.red,
    Colors.brown,
    Colors.black,
    Colors.pink,
    Colors.grey
  ];

  @override
  void initState() {
    super.initState();

    blockWidgets = new List();
    for (int i = 0; i < widgetColors.length; i++) {
      blockWidgets.add(
          BlockWidget(widgetId: i, widgetColor: widgetColors.elementAt(i)));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('AppBar'),
      ),
      body: WidgetStacks(
        key:ValueKey('WidgetStacks_${blockWidgets.length}'),
        blocks: blockWidgets,
      ),
    );
  }
}

const blockHeight = 100.0;
const blockWidth = 100.0;

class BlockWidget {
  int widgetId;
  Color widgetColor;

  BlockWidget({
    @required this.widgetId,
    @required this.widgetColor,
  });
}

class TransformedWidget extends StatefulWidget {
  final BlockWidget block;
  final int stackIndex;
  final List<BlockWidget> attachedBlocks;
  final Function() onDragCanceled;
  final Function() onDragStart;

  TransformedWidget({
    Key key,
    @required this.block,
    @required this.stackIndex,
    @required this.attachedBlocks, this.onDragCanceled, this.onDragStart,
  }):super(key: key);

  @override
  _TransformedWidgetState createState() => _TransformedWidgetState();
}

class _TransformedWidgetState extends State<TransformedWidget> {
  @override
  Widget build(BuildContext context) {
    return Transform(
      transform: Matrix4.identity()
        ..translate(
          widget.stackIndex * (blockHeight / 2),
          widget.stackIndex * (blockWidth / 2),
          0.0,
        ),
      child: Draggable<Map>(
        key: ValueKey(widget.stackIndex),
        onDragStarted: ()=>widget.onDragStart(),
        onDraggableCanceled: (_,__)=>widget.onDragCanceled(),
        child: _buildBlock(),
        feedback: WidgetStacks(
          key: ValueKey('WidgetStacks_${widget.attachedBlocks.length}'),
          blocks: widget.attachedBlocks,
        ),
        childWhenDragging: Container(),
      ),
    );
  }

  Widget _buildBlock() => Material(
          child: Container(
        height: blockHeight,
        width: blockWidth,
        color: widget.block.widgetColor,
        alignment: Alignment.centerLeft,
        child: Text(
          widget.block.widgetId.toString(),
          style: TextStyle(
            fontSize: 30.0,
            color: Colors.white,
          ),
        ),
      ),
    );
}

class WidgetStacks extends StatefulWidget {
  final List<BlockWidget> blocks;

  WidgetStacks({@required this.blocks, Key key}):super(key:key);

  @override
  _WidgetStacksState createState() => _WidgetStacksState();
}

class _WidgetStacksState extends State<WidgetStacks> {
  ValueNotifier<List<BlockWidget>> blocksToBeShownNotifier;

  @override
  void initState() {
    blocksToBeShownNotifier = ValueNotifier<List<BlockWidget>>(widget.blocks);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 5 * blockHeight,
      width: 5 * blockWidth,
      margin: EdgeInsets.all(2.0),
      child: ValueListenableBuilder<List<BlockWidget>>(
        valueListenable: blocksToBeShownNotifier,
        builder: (BuildContext context,List<BlockWidget> value, Widget child) {
        return Stack(
        children: value.map((block) {
          int index = value.indexOf(block);
          return TransformedWidget(
            key: ValueKey(block.widgetId),
            block: block,
            stackIndex: index,
            onDragStart:(){
              blocksToBeShownNotifier.value = widget.blocks.sublist(0, index);
            },
            onDragCanceled:(){
              blocksToBeShownNotifier.value = widget.blocks;
            },
            attachedBlocks: widget.blocks.sublist(index),
          );
        }).toList(),
      );
      },),
    );
  }
}

希望对您有所帮助,如有疑问,请发表评论。