Flutter 搜尋, 輪播, 列表構建
前言
上篇文章已說明寫flutter系列專案是在的想法, 已經完成了框架的搭建, 以及底部的導航的實現.
這篇文上介紹第一個導航頁面的佈局內容. 主要內容包括: 列表顯示, 搜尋框顯示, 輪播圖顯示
效果圖如下:

1.png
從上到下佈局開始介紹
搜尋框
首先在導航檔案中新增

2.png
首先新建TextFieldWidget類, 其中程式碼如下:
class TextFieldWidget extends StatelessWidget { Widget buildTextField() { // theme設定區域性主題 return Theme( data: new ThemeData(primaryColor: Colors.grey), child: new TextField( cursorColor: Colors.grey, // 游標顏色 // 預設設定 decoration: InputDecoration( contentPadding: const EdgeInsets.symmetric(vertical: 10.0), border: InputBorder.none, icon: Icon(Icons.search), hintText: "搜尋 flutter 元件", hintStyle: new TextStyle( fontSize: 14, color: Color.fromARGB(50, 0, 0, 0))), style: new TextStyle(fontSize: 14, color: Colors.black), ), ); } @override Widget build(BuildContext context) { return Container( // 修飾搜尋框, 白色背景與圓角 decoration: new BoxDecoration( color: Colors.white, borderRadius: new BorderRadius.all(new Radius.circular(5.0)), ), alignment: Alignment.center, height: 36, padding: EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 0.0), child: buildTextField(), ); } }
主要說明已在程式碼中註釋, 如有疑問可以討論
輪播圖
上網查詢了一下,採用的是flutter_swiper: ^1.0.6這個庫, 引入一下放到pubsec.yaml檔案下.即可使用,程式碼如下:
new Container( width: MediaQuery.of(context).size.width, height: 200, child: Swiper( itemCount: 3, itemBuilder: _swiperBuilder, pagination: new SwiperPagination( builder: DotSwiperPaginationBuilder( color: Colors.black54, activeColor: Colors.white, size: 5.0, activeSize: 5.0, )), scrollDirection: Axis.horizontal, autoplay: true, onTap: (index) => print('點選了第$index個')), ),
_swiperBuilder方法:
Widget _swiperBuilder(BuildContext context, int index) { return (Image.network("http://via.placeholder.com/350x150", fit: BoxFit.fill)); }
列表
new Expanded( child: new ListView.builder( itemCount: 10, itemBuilder: _listBuilder, ), )
_listBuilder方法:
Widget _listBuilder(BuildContext context, int index) { return new Container( padding: EdgeInsets.all(10.0), margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), decoration: new BoxDecoration( boxShadow: <BoxShadow>[ new BoxShadow( color: const Color(0x99000000), offset: new Offset(0.0, 0.5), blurRadius: 1.0, ), ], color: Colors.white, borderRadius: new BorderRadius.all(new Radius.circular(5.0)), ), child: new Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ new Expanded( child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Container( margin: new EdgeInsets.only(bottom: 10.0), child: new Text( "8篇文章, 再學不會flutter你來打我!", style: new TextStyle(fontSize: 14, color: Colors.black45), ), ), new Text( "我是作者", style: new TextStyle(fontSize: 14, color: Colors.black45), ), ], ), ), new Icon( Icons.keyboard_arrow_right, color: Colors.grey, ) ], ), ); }
以上全部會展現出效果圖的效果了.
重點講解
- 1,一般元件TextField, text, image. 沒有margin等屬性, 需要用container包含
- 2, Expanded會撐起寬度.
- 3, Theme可設定區域性主題. 一般在main中設定全域性主題
下篇
下篇介紹內容如下
- 1, 導航跳轉詳情頁面
- 2, 列表重新整理載入,
- 3, 網路資料請求