Skip to content

Instantly share code, notes, and snippets.

@Abion47
Created May 11, 2021 20:03
Show Gist options
  • Save Abion47/20f7e61681fdb178ba7fe81361b00182 to your computer and use it in GitHub Desktop.
Save Abion47/20f7e61681fdb178ba7fe81361b00182 to your computer and use it in GitHub Desktop.
Why StatefulWidgets need keys
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MyApp());
Color randomColor() {
Random r = Random();
return Color(0xFF000000 + r.nextInt(0x00FFFFFF));
}
class MyApp extends StatefulWidget {
@override
createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: TileList(),
);
}
}
class TileList extends StatefulWidget {
TileList({Key key}) : super(key: key);
@override
createState() => TileListState();
}
class TileListState extends State<TileList> {
List<Tile> tiles;
@override
void initState() {
super.initState();
tiles = List.generate(10, (i) => Tile());
}
void removeTile() {
setState(() {
// Remove the third tile
tiles.removeAt(2);
print(tiles.length);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tiles'),
),
body: ListView.builder(
itemCount: tiles.length,
itemBuilder: (context, i) {
return tiles[i];
}
),
floatingActionButton: FloatingActionButton(
onPressed: removeTile,
tooltip: 'Increment',
child: Icon(Icons.remove),
),
);
}
}
class Tile extends StatefulWidget {
Tile({Key key}) : super(key: key);
@override
createState() => TileState();
}
class TileState extends State<Tile> {
Color color;
@override
void initState() {
super.initState();
color = randomColor();
}
@override
Widget build(BuildContext context) {
return Container(
height: 150,
color: color,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment