我正在尝试在flutter中开发小型应用程序,以便我们可以像下面的图片一样向其容器中添加水果。
我已使用此参考资料开发了应用程序。 Flutter drag and drop
我能够执行下图所示的某些功能。
2)
从上面的图像中,我可以将其放在图像容器上,但不能按照我对容器的第一张图像的预期正确放置。
下面是我为实现此功能而执行的代码。很抱歉,如果我的代码不好,因为我当前正在学习抖动。
class ColorGame extends StatefulWidget {
ColorGame({Key key}) : super(key: key);
createState() => ColorGameState();
}
class ColorGameState extends State<ColorGame> {
/// Map to keep track of score
final Map<String, bool> score = {};
/// Choices for game
final Map choices = {
'?': Colors.green,
'?': Colors.yellow,
'?': Colors.orange
};
// Random seed to shuffle order of items.
int seed = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Score ${score.length} / 6'),
backgroundColor: Colors.pink),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () {
setState(() {
score.clear();
seed++;
});
},
),
body: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.end,
children: choices.keys.map((emoji) {
return Draggable<String>(
data: emoji,
child: Emoji(emoji: score[emoji] == true ? '✅' : emoji),
feedback: Emoji(emoji: emoji),
childWhenDragging: Emoji(emoji: '?'),
);
}).toList()),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children:
choices.keys.map((emoji) => _buildDragTarget(emoji)).toList()
..shuffle(Random(seed)),
)
],
),
);
}
Widget _buildDragTarget(emoji) {
return DragTarget<String>(
builder: (BuildContext context, List<String> incoming, List rejected) {
if (score[emoji] == true) {
return Container(
child: Stack(
children: <Widget>[
Center(
child: new Image.asset(
'assets/Banana_Container.png',
fit: BoxFit.fill,
),
),
Center(
child: Emoji(emoji:emoji),
),
],
),
);
} else {
if (choices[emoji] == Colors.yellow) {
return Container(
child: Image.asset('assets/Banana_Container.png'),
);
}
if (choices[emoji] == Colors.green) {
return Container(
child: Image.asset('assets/Apple_Container.png'),
);
}
if (choices[emoji] == Colors.orange) {
return Container(
child: Image.asset('assets/Orange_Container.png'),
);
}
}
},
onWillAccept: (data) => data == emoji,
onAccept: (data) {
setState(() {
score[emoji] = true;
plyr.play('success.mp3');
});
},
onLeave: (data) {},
);
}
}
class Emoji extends StatelessWidget {
Emoji({Key key, this.emoji}) : super(key: key);
final String emoji;
@override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: Container(
alignment: Alignment.center,
height: 100,
padding: EdgeInsets.all(10),
child: Text(
emoji,
style: TextStyle(color: Colors.black, fontSize: 50),
),
),
);
}
}
我如何才能正确地将水果放入容器中。如果您可以提供任何建议或参考来实现这一目标。
谢谢