Skip to content

Instantly share code, notes, and snippets.

@MoshDev
Created January 22, 2020 21:34
Show Gist options
  • Save MoshDev/c22198f43bc5a377c2e5094b1433730e to your computer and use it in GitHub Desktop.
Save MoshDev/c22198f43bc5a377c2e5094b1433730e to your computer and use it in GitHub Desktop.
import 'dart:math';
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: 'State Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<ItemData> items = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sample App"),
),
body: Container(
padding: EdgeInsets.all(16),
child: Stack(
children: <Widget>[
ListView.separated(
itemBuilder: (ctx, index) {
return ListItemStateless(
item: items[index],
);
},
separatorBuilder: (_, __) => Divider(),
itemCount: items.length),
Align(
alignment: Alignment.bottomLeft,
child: RaisedButton(
onPressed: () {
setState(() {
items = List.generate(items.length+1, (index)=> ItemData("Hello $index"));
});
},
child: Text("Add"),
),
),
Align(
alignment: Alignment.bottomRight,
child: RaisedButton(
onPressed: () {
setState(() {
items.clear();
});
},
child: Text("Reset"),
),
)
],
),
));
}
}
final List<Color> _colors = [
Colors.red,
Colors.amber,
Colors.blue,
Colors.green,
Colors.lightGreen,
Colors.yellow,
Colors.grey,
Colors.blueAccent,
Colors.purpleAccent
];
final Random _random = Random();
class ListItemStateless extends StatefulWidget {
final ItemData item;
ListItemStateless({Key key, this.item}) : super(key: key);
@override
_ListItemStatelessState createState() => _ListItemStatelessState();
}
class _ListItemStatelessState extends State<ListItemStateless> {
final Color _color = _colors[_random.nextInt(1000) % _colors.length];
@override
Widget build(BuildContext context) {
String text = "$this";
return SizedBox(
width: double.infinity,
height: 50,
child: Container(color: _color, child: Center(child: Text("${widget.item.title} $text"))),
);
}
}
class ItemData{
final String title;
ItemData(this.title);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment