image.png
官方例子
官方例子
以下代碼創(chuàng)建了一個(gè)單詞列表曙博,可以點(diǎn)擊收藏,點(diǎn)擊菜單路由跳轉(zhuǎn)到收藏列表
english_words
是需要引用的庫文件
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(new MyApp());
//核心方法
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Startup Name Generator',
theme: new ThemeData(
primaryColor: Colors.white,
),
home: new RandomWords(),
);
}
}
//它也可以在MyApp之外的文件的任何位置使用
class RandomWords extends StatefulWidget {
@override
createState() => new RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
final _suggestions = <WordPair>[];
final _saved = new Set<WordPair>(); //收藏列表(使用set保證元素不會(huì)重復(fù))
final _biggerFont = const TextStyle(fontSize: 18.0); //字體大小
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('這是一個(gè)列表'),
actions: <Widget>[
new IconButton(icon: new Icon(Icons.list),
onPressed: _pushSaved
)
],
),
body: _biuldSuggerstions(),
);
}
Widget _biuldSuggerstions(){ //創(chuàng)建列表
return new ListView.builder(
padding:const EdgeInsets.all(0),//內(nèi)容間距
itemBuilder: (context,i){
if(i.isOdd) return new Divider();
//語法 "i ~/ 2" 表示i除以2轴脐,但返回值是整形(向下取整),比如i為:1, 2, 3, 4, 5
//時(shí)宫患,結(jié)果為0, 1, 1, 2, 2麦到, 這可以計(jì)算出ListView中減去分隔線后的實(shí)際單詞對(duì)數(shù)量
final index = i ~/ 2;
if (index >= _suggestions.length){
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
},
);
}
Widget _buildRow(WordPair pair){ //創(chuàng)建列表元素
final alreadySaved = _saved.contains(pair);
return new ListTile(
title : new Text(
pair.asPascalCase,
style: _biggerFont,
),
trailing: new Icon( //類似cell的尾部視圖
alreadySaved ? Icons.favorite : Icons.favorite_border,//系統(tǒng)自帶的圖標(biāo)
color: alreadySaved ? Colors.red : null,
),
onTap: (){//點(diǎn)擊的時(shí)候判斷是否已經(jīng)在數(shù)組中,如果在就刪除歌溉,沒有就添加
setState(() {
if(alreadySaved){
_saved.remove(pair);
}else {
_saved.add(pair);
}
});
},
);
}
//路由跳轉(zhuǎn)
void _pushSaved() {
Navigator.of(context).push(
//這里是臨時(shí)創(chuàng)建了一個(gè)新頁面
new MaterialPageRoute(
builder: (context){
final tiles = _saved.map(
(pair){
return new ListTile(
title: new Text(
pair.asPascalCase,
style: _biggerFont,
),
);
}
);
final divided = ListTile.divideTiles(
context: context,
tiles: tiles,
).toList();
return new Scaffold(
appBar: new AppBar(
title: new Text('Saved Suggestions'),
),
body: new ListView(children: divided),
);
},
),
);
}
}
筆記
ListView:類似TableView
ListTile:類似Cell
APP頁面跳轉(zhuǎn)
Navigator.of(context).push(route)