Skip to content

Instantly share code, notes, and snippets.

@piedcipher
Last active February 12, 2020 19:38
Show Gist options
  • Save piedcipher/6f373fc90ea482237a3ccba6c86522e2 to your computer and use it in GitHub Desktop.
Save piedcipher/6f373fc90ea482237a3ccba6c86522e2 to your computer and use it in GitHub Desktop.
ListTile Favorite Demo - StackOverflow
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _itemLength;
List<bool> _isFavorited = [];
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('ListTile Favorite Demo'),
),
body: _itemLength != null
? ListView.builder(
itemCount: _itemLength,
itemBuilder: (context, index) => ListTile(
title: Text(index.toString()),
trailing: IconButton(
onPressed: () => setState(
() => _isFavorited[index] = !_isFavorited[index]),
icon: _isFavorited[index]
? Icon(Icons.star)
: Icon(Icons.star_border),
),
),
)
: StreamBuilder(
initialData: 0,
stream: Stream.fromFuture(
Future.delayed(
Duration(
seconds: 1,
),
() => 20),
),
builder: (context, snapshot) {
if (snapshot.data > 0) {
_itemLength = snapshot.data;
_isFavorited =
List<bool>.generate(_itemLength, (_) => false);
return ListView.builder(
itemCount: _itemLength,
itemBuilder: (context, index) => ListTile(
title: Text(index.toString()),
trailing: IconButton(
onPressed: () => setState(
() => _isFavorited[index] = !_isFavorited[index]),
icon: _isFavorited[index]
? Icon(Icons.star)
: Icon(Icons.star_border),
),
),
);
}
return Center(child: CircularProgressIndicator());
}),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment