【问题标题】:There are some parts that I don't understand well about Flutter's Key关于 Flutter 的 Key 有一些地方我不是很了解
【发布时间】: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。你能告诉我示例代码吗?感谢您的回复。
  • 我实际上并没有举例,我只是注意到你的问题。你想让我做一个吗?
  • 我将其发布为答案。

标签: flutter flutter-widget


【解决方案1】:

您将颜色存储在KeyPractice 的State 中。他们使用的示例将其存储在孩子的State 中,在您的情况下为:StatefulColorfulTile。

下面是使用键正确重新定位小部件的示例,就像您尝试做的那样。我的示例最终与medium article 上显示的非常相似。在此处删除键可防止小部件反映颜色交换,但使用键可实现预期行为。

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

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({Key key}) : super(key: key);
  
  @override
  _StatefulColorfulTileState createState() => _StatefulColorfulTileState();
}

class _StatefulColorfulTileState extends State<StatefulColorfulTile> {
  final Color myColor = UniqueColorGenerator.getColor();
  
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      height: 100,
      color: myColor,
    );
  }
}

class KeyPractice extends StatefulWidget {
  @override
  _KeyPracticeState createState() => _KeyPracticeState();
}

class _KeyPracticeState extends State<KeyPractice> {
  List<Widget> tiles;

  @override
  void initState() {
    super.initState();
    tiles = [
      StatefulColorfulTile(key: UniqueKey()),
      StatefulColorfulTile(key: UniqueKey()),
    ];
  }

  @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));
          });
        },
      ),
    );
  }
}


class UniqueColorGenerator {
  static Random random = new Random();
  static Color getColor() {
    return Color.fromARGB(255, random.nextInt(255), random.nextInt(255), random.nextInt(255));
  }
}

【讨论】:

  • 抱歉回复晚了。我很高兴你回复了。我会根据你告诉我的再次研究它。我正在考虑写一篇关于这个的博客,我可以透露代码的来源并引用它吗?
  • @Jay-flow 你可以根据licenses for posts on SO 未经我的许可这样做,只要你给予适当的信任。但是,我必须提到,我从其他地方获取了颜色生成器,它最终看起来非常与我链接的中篇文章中的代码相似。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
相关资源
最近更新 更多