Flutter 模仿微信讀書實現(xiàn)案例

前言:

各位同學(xué)大家好,有一段時間沒有給大家更新博客了,最近使用flutter跨平臺寫了一個模仿微信讀書app demo版本(模仿其中部分經(jīng)典頁面不是全部)覺得有幾個點值得分享一下,趁著今天放假,就發(fā)文章分線給大家,那么廢話不多說我們正式開始

效果圖:

Screenrecorder-2020-09-12-13-41-20-726[00_00_00--00_00_20].gif

準(zhǔn)備工作:

需要安裝flutter的開發(fā)環(huán)境:大家可以去看看之前的教程:
1 win系統(tǒng)flutter開發(fā)環(huán)境安裝教程: http://www.itdecent.cn/p/152447bc8718
2 mac系統(tǒng)flutter開發(fā)環(huán)境安裝教程:http://www.itdecent.cn/p/bad2c35b41e3

具體實現(xiàn):

QQ截圖20200912135506.png

效果分析:
我們看到底部的tab和上面的卡片形成了聯(lián)動我們點擊下面的button 和滑動都可以聯(lián)動,flutter中底部的tab切換我們都是用 bottomNavigationBar 組件來實現(xiàn),但是要實現(xiàn)聯(lián)動我們需要配合PageView 來實現(xiàn):
我們看下 TabNavigator中的代碼實現(xiàn)

import 'package:flutter/material.dart';
import 'content_pager.dart';
/**
 * 創(chuàng)建人:xuqing
 * 創(chuàng)建時間:2020年2月7日16:26:18
 *
 */


class TabNavigator extends StatefulWidget {
  TabNavigator({Key key}) : super(key: key);

  @override
  _TabNavigatorState createState() {
    return _TabNavigatorState();
  }
}

class _TabNavigatorState extends State<TabNavigator> {
  final _defaultColor=Colors.grey;  //未選中
  final _activeColor=Colors.blue;  //選中的顏色
  int  _currentIndex=0;
  final ContentPagerConteroller _contentPagerConteroller=new ContentPagerConteroller();
  @override
  void initState() {
    super.initState();
}
  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
             Color(0xffedeef0),
             Color(0xffe6e7E9),
            ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter
          )
        ),
        child: ContentPager(
          contentPagerConteroller: _contentPagerConteroller,
          onPageChanged: (int index){
            setState(() {
              _currentIndex=index;
            });
          },
        )

      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          _bottomItem("本周", Icons.folder, 0),
          _bottomItem("分享", Icons.explore, 1),
          _bottomItem("免費", Icons.donut_small, 2),
          _bottomItem("長按", Icons.person, 3),
        ],
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        onTap: (index){
          _contentPagerConteroller.jumpTopage(index);
          setState(() {
            _currentIndex=index;
          });
        },
      ),
    );

  }
  //封裝底部的tab
   _bottomItem(String title, IconData icon ,int index){
      return BottomNavigationBarItem(
        icon: Icon(
          icon,
          color: _defaultColor,
        ),
        activeIcon: Icon(
          icon,
          color: _activeColor,
        ),

       title: Text(title,style:TextStyle(
         color:_currentIndex!=index?_defaultColor:_activeColor
       ) ,)
      );
   }
}

TabNavigator 里面我們通過 Decoration 設(shè)置背景漸變顏色,然后通過 bottomNavigationBar 設(shè)置底部的tab導(dǎo)航 切換的效果,TabNavigator 中整個布局我們上面一部分是一個ContentPager ()的widget
然后底部是一個 bottomNavigationBar 組件構(gòu)成

ContentPager中具體里面的實現(xiàn)

ContentPager類中我們主要使用了 PageView 組件 來裝在我們要顯示的四個widget頁面

Column(
      children: <Widget>[
       CustomAppbar(),
        Expanded(
          child: PageView(
            onPageChanged: widget.onPageChanged,
            controller: _pageController,
            children: <Widget>[
              _wrapItem(CardRecommend()),
              _wrapItem(CardShare()),
              _wrapItem(CardFree()),
              _wrapItem(CardSpecial()),
            ],
          ),
        )
      ],
    );

然后我們在PageView 的 controller屬性中設(shè)置顯示比例:
這里我們設(shè)置為0.8就呈現(xiàn)我們想要的卡片的效果 要是們設(shè)置成1的話就撐滿屏幕寬高這個要看你具求了
封裝 _wrapItem 方法根據(jù)下標(biāo)index來返回對應(yīng)的Widget

 controller: _pageController,
    //視圖比例
  PageController _pageController=PageController(
    viewportFraction: 0.8,
  );

封裝 _wrapItem 方法根據(jù)下標(biāo)index來返回對應(yīng)的Widget

  Widget   _wrapItem(Widget widget){
    return  Padding(padding: EdgeInsets.all(10.0),
       child: widget
       );

  }

定義兩個成員變量 onPageChanged contentPagerConteroller 用來回調(diào)給 TabNavigator

  final ValueChanged<int>onPageChanged;
  final ContentPagerConteroller contentPagerConteroller;

onPageChanged 用來控制 滑動跟tab聯(lián)動
contentPagerConteroller 用來控制點擊底部的tab上的卡片Widget 切換
具體調(diào)用onPageChanged 調(diào)用

child: ContentPager(
          contentPagerConteroller: _contentPagerConteroller,
          onPageChanged: (int index){
            setState(() {
              _currentIndex=index;
            });
          },
        )

ContentPagerConteroller 類中小技巧

class ContentPagerConteroller{
  PageController _pageController;
  void  jumpTopage(int page){
    //dart 編程技巧 安全調(diào)用
    _pageController?.jumpToPage(page);
  }
}

這個樣我們這個tab切換和聯(lián)通效果我們就試下了
ContentPager完整代碼

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'custom_appbar.dart';
import 'card_recommend.dart';
import 'card_share.dart';
import 'care_free.dart';
import 'card_special.dart';






class ContentPager extends StatefulWidget {
  final ValueChanged<int>onPageChanged;
  final ContentPagerConteroller contentPagerConteroller;
   //構(gòu)造方法 可選參數(shù)
  ContentPager({Key key, this.onPageChanged, this.contentPagerConteroller}) : super(key: key);
  @override
  _ContentPagerState createState() {
    return _ContentPagerState();
  }
}
class _ContentPagerState extends State<ContentPager> {
    //視圖比例
  PageController _pageController=PageController(
    viewportFraction: 0.8,
  );
  static List<Color>_colorlist=[
    Colors.blue,
    Colors.red,
    Colors.deepOrange,
    Colors.teal,
  ];
  @override
  void initState() {
    // TODO: implement initState
    if(widget.contentPagerConteroller!=null){
      widget.contentPagerConteroller._pageController=_pageController;
    }
    _statusBar();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
       CustomAppbar(),
        Expanded(
          child: PageView(
            onPageChanged: widget.onPageChanged,
            controller: _pageController,
            children: <Widget>[
              _wrapItem(CardRecommend()),
              _wrapItem(CardShare()),
              _wrapItem(CardFree()),
              _wrapItem(CardSpecial()),
            ],
          ),
        )

      ],
    );
  }

  Widget   _wrapItem(Widget widget){
    return  Padding(padding: EdgeInsets.all(10.0),
       child: widget
       );

  }

   _statusBar(){
     SystemUiOverlayStyle  uiOverlayStyle=SystemUiOverlayStyle(
       systemNavigationBarColor: Color(0xFF000000),
       systemNavigationBarDividerColor: null,
       statusBarColor: Colors.transparent,
       systemNavigationBarIconBrightness: Brightness.light,
       statusBarIconBrightness: Brightness.dark,
       statusBarBrightness: Brightness.light,
     );
     SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
   }
}

class  ContentPagerConteroller{
  PageController _pageController;
  void  jumpTopage(int page){
    //dart 編程技巧 安全調(diào)用
    _pageController?.jumpToPage(page);
  }
}

頂部appbar的實現(xiàn) :

我這邊是自定義了一個 widget實現(xiàn)的:
布局不難我們寫了一個 Container 盒子組件然后里面嵌套Row組件的實現(xiàn)的

import 'package:flutter/material.dart';
/***
 *  創(chuàng)建人 :xuqing
 *  創(chuàng)建時間:2020年2月9日15:53:54
 *  類說明:自定義appbar
 *
 *
 */
class CustomAppbar extends StatefulWidget {
  CustomAppbar({Key key}) : super(key: key);
  @override
  _CustomAppbarState createState() {
    return _CustomAppbarState();
  }
}
class _CustomAppbarState extends State<CustomAppbar> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    double paddingtop=MediaQuery.of(context).padding.top;
    return Container(
      margin: EdgeInsets.fromLTRB(20, paddingtop+10, 20, 5),
      padding: EdgeInsets.fromLTRB(20, 30, 20, 5),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(19),color: Colors.white60
      ),
      child: Row(
        children: <Widget>[
          Icon(
            Icons.search,
            color: Colors.grey,
          ),
          Expanded(
           child: Text("長安十二實誠",style:
             TextStyle(
               fontSize: 15,
               color: Colors.grey
             ),),
          ),
          Container(
            width: 1,
            height: 20,
            margin: EdgeInsets.only(right: 13),
            decoration: BoxDecoration(
              color: Colors.grey
            ),
          ),
          Text(
            "書城",
            style: TextStyle(
              fontSize: 13,
            ),
          )
        ],
      ),
    );
  }
}

具體卡片頁面的實現(xiàn):

效果圖:

QQ截圖20200912143056.png

QQ截圖20200912143139.png

我們分寫發(fā)現(xiàn)正面這部分基本是重復(fù)出現(xiàn)的于是我們就寫了一個 BaseCared這樣一個基類來封裝上面重復(fù)的組件

import 'package:flutter/material.dart';

/**
 *
 *  創(chuàng)建人:xuqing
 *  創(chuàng)建時間:2020年2月12日23:10:48
 *  類說明:卡片基類
 *
 *
 *
 */

class BaseCared extends StatefulWidget {
  BaseCared({Key key}) : super(key: key);
  @override
  BaseCaredState createState() {
    return BaseCaredState();
  }
}
class BaseCaredState extends State<BaseCared> {
  Color subTitleColor=Colors.grey;
  Color bottomTitleColor=Colors.grey;
  @override
  void initState() {
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return PhysicalModel(color: Colors.transparent,
      borderRadius: BorderRadius.circular(6),
      clipBehavior: Clip.antiAlias,
      child: Container(
        decoration: BoxDecoration(color: Colors.white),
        child: Column(
          children: <Widget>[
           topContent(),
            bottomContent()
          ],
        ),
      ),
     );
  }
  topContent(){
    return Padding(
      padding: EdgeInsets.only(left: 20,top: 26,bottom: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              topTitle(""),
              topTtile2(),
            ],
          ),
          subTitle(""),
        ],
      ),
    );
  }
  bottomContent(){
  return Container();
  }
 Widget subTitle(String str){
    return Padding(
      padding: EdgeInsets.only(top: 5),
      child: Text(
          str,style: TextStyle(
          fontSize: 11,
        color: subTitleColor
      ),
      ),
    );
  }
  topTitle(String title){
  return Text(title,style: TextStyle(
    fontSize: 22
      ),);
  }
  topTtile2( ){
   return Container();
  }
  bottomTitle(String title){
    return Text(title,style: TextStyle(
      fontSize: 11,
      color: bottomTitleColor
    ),
    textAlign: TextAlign.center,
    );
  }
}

我們在BaseCared 類中分別定義了 subTitle topTitle topTtile2 bottomTitle 等方法讓其他集成BaseCared 基類的組件類來重寫調(diào)用
具體調(diào)用

 @override
  topTitle(String title) {
    // TODO: implement topTitle
    return super.topTitle("本周推薦");
  }

   @override
  Widget subTitle(String str) {
    // TODO: implement subTitle
    return super.subTitle("送你一張無限卡.全場數(shù)據(jù)免費讀");
  }

由于篇幅問題各個卡片頁面的具體實現(xiàn)我就不展開講了有興趣的朋友可以下載完整的代碼參考,重點是BaseCared 基類封裝的技巧和pageview 滑動聯(lián)動的實現(xiàn)技巧,到此我們的flutter模仿微信讀書app的案例就講完了

最后總結(jié):

這個模仿微信讀書app項目并不難 但是其中巧妙的運用了一些dart 語言編程技巧和一些組件的配合使用
我覺得有必要分享給大家 ,大家如果覺得文章還不錯麻煩給我一個star 和轉(zhuǎn)發(fā)(我也是一名90后程序員)謝謝大家

項目地址:

碼云:https://gitee.com/qiuyu123/flutter_wechatredbook

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容