[Flutter / Key] setState를 해도 위젯순서가 바뀌지 않는 이유를 Key로 해결해보자

왜 위젯순서가 안바뀌지....? 😢

Row, Column, 특히 ListView에서 데이터들의 순서나 위젯 순서를 바꿔야 할 때가 있다.

예를 들어보자.

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  List<Widget> _tiles = [_Tile(), _Tile()];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(child: Row(children: _tiles)),
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.error),
          onPressed: () {
            _tiles.insert(1, _tiles.removeAt(0));
            setState(() {});
          },
        ),
      ),
    );
  }
}

class _Tile extends StatelessWidget {
  _Tile({Key? key}) : super(key: key);

  final Color color = Color(Random().nextInt(0xffffffff));

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(50),
      color: color,
      child: FlutterLogo(),
    );
  }
}

무제 (3).gif

잘 된다.

_Tile클래스를 StatefulWidget으로 변경하면 어떤 일이 일어날까?

...
class _Tile extends StatefulWidget {
  _Tile({Key? key}) : super(key: key);

  @override
  State<_Tile> createState() => _TileState();
}

class _TileState extends State<_Tile> {
  final Color color = Color(Random().nextInt(0xffffffff));

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(50),
      color: color,
      child: FlutterLogo(),
    );
  }
}

무제 (1).gif