Skip to content

Instantly share code, notes, and snippets.

@ngouy
Created January 12, 2020 20:43
Show Gist options
  • Save ngouy/841bebbc3824374d711f66290e1b71ce to your computer and use it in GitHub Desktop.
Save ngouy/841bebbc3824374d711f66290e1b71ce to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Startup Name Generator',
home: RandomWords(),
);
}
}
class RandomWordsState extends State<RandomWords> {
final List<WordPair> _suggestions = <WordPair>[];
final List<WordPair> _saved = <WordPair>[]; // Add this line.
final TextStyle _fontStyle = const TextStyle(fontSize: 18);
Widget _buildWordsList(WordPair itemAt(int index)) {
return ListView.builder(
padding: const EdgeInsets.all(16),
itemBuilder: (BuildContext context, int i) {
final int index = i ~/ 2;
final item = itemAt(index);
if (item == null) {
return null;
}
if (i.isOdd) {
return Divider();
}
return _buildRow(item);
},
);
}
Widget _buildRow(WordPair pair) {
final bool alreadySaved = _saved.contains(pair); // Add this line.
return ListTile(
title: Text(
pair.asPascalCase,
style: _fontStyle,
textAlign: TextAlign.center,
),
trailing: Icon(
alreadySaved ? Icons.favorite : Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
),
onTap: () {
setState(() {
if (alreadySaved) {
_saved.remove(pair);
} else {
_saved.add(pair);
}
});
},
);
}
WordPair _suggestionsBuilder(int index) {
if (index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(10));
}
return _suggestions[index];
}
WordPair _favoriteWordGetter(int index) {
if (index < _saved.length) {
return _saved[index];
}
return null;
}
void _pushSaved() {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Favorites suggestions"),
),
body: _buildWordsList(_favoriteWordGetter));
},
),
);
}
@override // Add from this line ...
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Startup Name Generator'),
actions: <Widget>[
IconButton(icon: Icon(Icons.list), onPressed: _pushSaved)
],
),
body: _buildWordsList(_suggestionsBuilder),
);
}
}
class RandomWords extends StatefulWidget {
@override
RandomWordsState createState() => RandomWordsState();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment