Flutter资源
我们的项目中一般有很多图片资源,那么图片放在Flutter的什么位置呢?首先把资源复制COM + C
然后选中Flutter的根目录COM + V此时会弹出提示:
选择OK.接着来到项目的pubspecy.yaml文件, 这里不光存放图片还有今后要用的包也是在这里配置。
找到这行注释放开,注意这里一定要注意空格的格式,这里报错是因为多了两个空格,我们需要跟上面对齐
正确的写法是这样,注明图片的路径在images下
安卓资源配置
在iOS中有1x/2x/3x的概念,但是在安卓中跟iOS有点不一样
底部BottomNavigationBar
1.来到main.dart的文件下,我们这里自定义MaterialApp的home小组件,其他的暂时都不用动。
2.自定义RootPage底部的点击会图片的颜色和文字的颜色,所以这里设计的就需要是一个有状态的Widget
import 'package:flutter/material.dart';class RootPage extends StatefulWidget {const RootPage({Key? key}) : super(key: key);@override_RootPageState createState() => _RootPageState();}class _RootPageState extends State<RootPage> {@overrideWidget build(BuildContext context) {return Scaffold(bottomNavigationBar: BottomNavigationBar(items: [BottomNavigationBarItem(icon: Icon(Icons.add), label: '微信'),BottomNavigationBarItem(icon: Icon(Icons.add), label: '通讯录'),BottomNavigationBarItem(icon: Icon(Icons.add), label: '发现'),BottomNavigationBarItem(icon: Icon(Icons.add), label: '我'),],),);}}
设置三个Item运行没有问题,但是一旦设置了四个Item�运行之后我们发现此时的页面成了这样的:
点击下面可以看到是有东西的,只是没有显示出来,这是因为这里少了一个type,给BottomNavigationBar设置type: BottomNavigationBarType.fixed�,之后运行效果出来了
我们还发现当前的BottomNavigationBar有一个currentIndex属性,默认值给的是0,我们想要它动态变化。同时这个BottomNavigationBar还有一个onTap事件,点击查看发现这里有个标记点击的是哪一个的BottomNavigationBarItem
typedef ValueChanged<T> = void Function(T value);
我们把这个index传递给当前的_currentIndex,此时代码就成了这样
class _RootPageState extends State<RootPage> {int _currentIndex = 0;@overrideWidget build(BuildContext context) {return Scaffold(bottomNavigationBar: BottomNavigationBar(onTap: (index) {setState(() {_currentIndex = index;});},type: BottomNavigationBarType.fixed,fixedColor: Colors.green,currentIndex: _currentIndex,items: [BottomNavigationBarItem(icon: Icon(Icons.add), label: '微信'),BottomNavigationBarItem(icon: Icon(Icons.add), label: '通讯录'),BottomNavigationBarItem(icon: Icon(Icons.add), label: '发现'),BottomNavigationBarItem(icon: Icon(Icons.add), label: '我'),],),);}}
对应BottomNavigationBarItem的Scaffold
点击下面的BarItem的时候,我们希望当前的页面的Body是对应的Scaffold的一个组件,所以此时生成四个page.dart
回到RootPage来,我们把这四个子Page装在一个数组里面,然后根据当前的_current的下标来取出做为当前的Body
此时运行效果
细节完善
点击BarItem的时候有一个水波纹的动画,这个是系统自带的我们可以去掉。
theme: ThemeData(primarySwatch: Colors.blue, //整个App的主题色highlightColor: Color.fromRGBO(1, 0, 0, 0),splashColor: Color.fromRGBO(1, 0, 0, 0)),
默认选中的时候字体有放大的效果:默认选中的字体是14,我们这里修改为12, 默认么有选中的字体是12。
BottomNavigationBar(selectedFontSize: 12.0,)
3.把图片都替换成资源里面的图片
BottomNavigationBarItem(icon: Image(width: 20,height: 20,image: AssetImage('images/tabbar_chat.png')), // 正常显示activeIcon: Image(width: 20,height: 20,image: AssetImage('images/tabbar_mine_hl.png'), // 选中显示),label: '微信'),
把整个App的主题设置成原谅绿
ThemeData(primarySwatch: Colors.green,highlightColor: Color.fromRGBO(1, 0, 0, 0),splashColor: Color.fromRGBO(1, 0, 0, 0)),

好了,最初的框架已经搭建好了。
