Flutter学习

Flutter学习--项目实战(一)

2020-04-24  本文已影响0人  文小猿666

众所周知目前国内大多数App的根视图是由下图形式组成的,
所以这一节我们来做一个类似微信的App框架,实现点击下方tabbar按钮来切换界面的功能。


图片.png

我们要做一个项目的话就需要考虑代码的可读性了。如果项目分为四个模块的话,我会创建一个rootpage来处理四个首层控制器问题。
本节的重点就是这个类。


图片.png

代码:

import 'package:flutter/material.dart';
import 'wechat_page.dart';
import 'contact_page.dart';
import 'discovery_page.dart';
import 'mine_page.dart';

class root_page extends StatefulWidget {
  @override
  _root_pageState createState() => _root_pageState();
}

class _root_pageState extends State<root_page> {
  final List<BottomNavigationBarItem> _bottomItems = [
    BottomNavigationBarItem(
        icon: Icon(Icons.chat),
        title: Text('Wechat')
    ),
    BottomNavigationBarItem(
        icon: Icon(Icons.contacts),
        title: Text('Contact')
    ),
    BottomNavigationBarItem(
        icon: Icon(Icons.find_in_page),
        title: Text('Discovery')
    ),
    BottomNavigationBarItem(
        icon: Icon(Icons.sentiment_dissatisfied),
        title: Text('Mine')
    ),
  ];
  final List<Scaffold> _scaffoldItems = [
    Scaffold(
      appBar: AppBar(title: Text('Wechat'),),
      body: WechatPage(),
    ),
    Scaffold(
      appBar: AppBar(title: Text('Contact'),),
      body: ContactPage(),
    ),
    Scaffold(
      appBar: AppBar(title: Text('Discovery'),),
      body: DiscoveryPage(),
    ),
    Scaffold(
      appBar: AppBar(title: Text('Mine'),),
      body: MinePage(),
    )
  ];
  int _currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        onTap: (int index){
          _currentIndex = index;
          setState(() {

          });
        },
        type: BottomNavigationBarType.fixed,
        items:_bottomItems,
        fixedColor: Colors.red,
        currentIndex: _currentIndex,
      ),
      body: _scaffoldItems[_currentIndex],
    );
  }
}

bottomNavigationBar

BottomNavigationBarType
有移动开发经验的话很容易看懂这段代码,在scaffold中添加类似于tabbar的组件bottomNavigationBar,设置type

enum BottomNavigationBarType {
  fixed,
  shifting,
}

BottomNavigationBarType.fixed 被选中后就会切换按钮的显示状态,他的另一个属性shifting很有意思,好像iOS中没有这种效果,感兴趣的同学可以自己去试一下。

items

  /// Defines the appearance of the button items that are arrayed within the
  /// bottom navigation bar.
  final List<BottomNavigationBarItem> items;

他需要返回一个BottomNavigationBarItem数组。
即界面下方的四个“按钮”。

fixedColor
为一个颜色值,为下方“按钮”选中后的颜色

currentIndex
他是设置当前哪一个“按钮”被选中的属性

body

这是Scaffold的属性,我们点击不同的底部“按钮”,来显示不同的界面靠的就是他

body: _scaffoldItems[_currentIndex],

最后实现的效果如下所示:

图片.png
图片.png

真的是很神奇呢。

上一篇 下一篇

猜你喜欢

热点阅读