GetX实现底部菜单切换
学习了Flutter两个月,看过无数大神的视频于文章,发现在状态管理与框架方面GetX的优势在于代码量少,书写逻辑利于我这样的小白用户理解。
目前在自己完成一个独立的项目,笔记将详细记录学习过程中遇到的问题与解决方法。
依赖
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.0
#GetX
get: ^3.24.0
#底部菜单
custom_navigation_bar: ^0.6.0
底部菜单交互使用了custom_navigation_bar,因为主要是理解GetX实现切换的逻辑,所以用已有的组件实现比较快。
controller
import 'package:get/get.dart';
class ApplicationController extends GetxController {
///当前Tap页码
var selectedIndex = 0.obs;
// 显示页面对应页码
void onBottomNavigationBar(int index) {
selectedIndex.value = index;
}
}
view
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:newspmbear_app/page/application/application_controller.dart';
import 'package:newspmbear_app/page/find/find_view.dart';
import 'package:newspmbear_app/page/home/home_view.dart';
import 'package:custom_navigation_bar/custom_navigation_bar.dart';
import 'package:newspmbear_app/page/my/my_view.dart';
import 'package:newspmbear_app/page/video/video_view.dart';
class ApplicationPage extends StatelessWidget {
final ApplicationController applicationController =
Get.put(ApplicationController());
//底部菜单
Widget _buildBottomNavigationBar() {
return Obx(
() => CustomNavigationBar(
iconSize: 28.0,
selectedColor: Color(0xff040307),
strokeColor: Color(0x30040307),
unSelectedColor: Color(0xffacacac),
backgroundColor: Colors.white,
items: [
CustomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("首页"),
),
CustomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
title: Text("视频"),
),
CustomNavigationBarItem(
icon: Icon(Icons.lightbulb_outline),
title: Text("发现"),
),
CustomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text("我的"),
),
],
//获取当前按钮数值
currentIndex: applicationController.selectedIndex.value,
//切换当前页面
onTap: applicationController.onBottomNavigationBar,
),
);
}
@override
Widget build(BuildContext context) {
ScreenUtil.init(context,
designSize: Size(375, 812), allowFontScaling: true);
List<Widget> _getPageView = [
HomePage(),
VideoPage(),
FindPage(),
MyPage(),
];
return Scaffold(
// 显示对应的页面
body: Obx(() =>
_getPageView.elementAt(applicationController.selectedIndex.value)),
bottomNavigationBar: _buildBottomNavigationBar(),
);
}
}