【发布时间】:2020-11-09 22:24:04
【问题描述】:
我是在看了一个解释 Flutter's Key 的视频后练习的。
https://api.flutter.dev/flutter/foundation/Key-class.html
此视频展示了一个使用特定颜色更改容器位置的示例。 (约 1 分 50 秒)
在视频中,statefulwidget 说没有密钥,位置不会改变。
但我自己编写了示例代码,并确认它可以在没有为有状态小部件提供密钥的情况下工作。
我想我写错了示例代码。下面是我写的代码。
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',
home: KeyPractice(),
);
}
}
class StatefulColorfulTile extends StatefulWidget {
StatefulColorfulTile({@required this.color});
final Color color;
@override
_StatefulColorfulTileState createState() => _StatefulColorfulTileState();
}
class _StatefulColorfulTileState extends State<StatefulColorfulTile> {
@override
Widget build(BuildContext context) {
return Container(
width: 100,
height: 100,
color: widget.color,
);
}
}
class KeyPractice extends StatefulWidget {
@override
_KeyPracticeState createState() => _KeyPracticeState();
}
class _KeyPracticeState extends State<KeyPractice> {
List<Widget> tiles;
@override
void initState() {
super.initState();
tiles = [
StatefulColorfulTile(
color: Colors.blueAccent,
),
StatefulColorfulTile(
color: Colors.amber,
),
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Row(
children: tiles,
),
),
floatingActionButton: FloatingActionButton(
child: Icon(
Icons.autorenew,
),
onPressed: () {
setState(() {
tiles.insert(1, tiles.removeAt(0));
});
},
),
);
}
}
以上代码相互切换位置。
当视频中的有状态小部件未分配键时,小部件如何相互重新定位的示例会发生什么情况?
而且我知道该密钥仅适用于 Stateful 小部件,Stateless 是否使用该密钥?
我知道 Key 仅适用于 Stateful 小部件。我想知道无状态小部件是否使用密钥。
如果我理解错了,请教我。
【问题讨论】:
-
您将颜色存储在
KeyPractice的State中。他们使用的示例将其存储在孩子的状态中,在您的情况下:StatefulColorfulTile。 -
我以为是问题,所以给子widget分配了一个颜色状态,但还是换了对方的widget。你能告诉我示例代码吗?感谢您的回复。
-
我实际上并没有举例,我只是注意到你的问题。你想让我做一个吗?
-
我将其发布为答案。