Creating My First App

If you follow the tutorial on Flutter’s website, you’ll get a product that looks like this.

The Final Product

The app displays a list of randomly generated names and allows you to favorite and unfavorite them. Simple enough.

How it works

The guide wants you to make a random word StatefulWidget in the same file as your main method, but i hate how cluttered that gets so i put it in it’s own file. Notice that this Widget is Stateful and not Stateless because the user interacts with this and I wanted to track changes to our state.

class RandomWords extends StatefulWidget {



@override

State createState() => new RandomWordsState();

} class RandomWordsState extends State<RandomWords> {

final _suggestions = <WordPair>[];

final _saved = new Set<WordPair>();

final _bigFont = const TextStyle(fontSize: 18.0);

}

Note that we can put two classes in the same file (for better or for worse).

Next, I overrode the build function to Scaffold up my page.

@override

Widget build(BuildContext context) {

return new Scaffold(

appBar: new AppBar(

title: new Text('Name Generator List'),

),

body: _buildSuggestions(),

);

}

After this was complete, I added a ListView (nothing changed there) and called build on it to override the rows to my liking. This listview is very similar to Android’s one and comes with all the same functionality. A point of interest here, you have to add the divider yourself if you want your rows to be visibly separated from one another.

Widget _buildSuggestions() {

return new ListView.builder(

padding: const EdgeInsets.all(16.0),

itemBuilder: (context, i) {

if (i.isOdd) return new Divider();



final index = i ~/ 2;

if (index >= _suggestions.length) {

_suggestions.addAll(generateWordPairs().take(10));

}

return _buildRow(_suggestions[index]);

},

);

}

Finally, for every row I want to create, _buildRow is called which returns a ListTile. I modify title, trailing, and onTap to style and change our state of our saved words.

Widget _buildRow(WordPair pair) {



final alreadySaved = _saved.contains(pair);



return new ListTile(

title: new Text(

pair.asPascalCase,

style: _bigFont,

),

trailing: new Icon(

alreadySaved ? Icons.favorite : Icons.favorite_border,

color: alreadySaved ? Colors.red : null,

),

onTap: () {

setState(() {

if (alreadySaved) {

_saved.remove(pair);

} else {

_saved.add(pair);

}

});

}

);

}

Watch how simplified the home screen got!