我正在尝试创建一个如下图所示的简单应用程序:
按钮应该可以切换 Widget1\Widget2。
我编写了以下代码(可直接复制粘贴):
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
initialBinding: HomeBinding(),
initialRoute: '/widget1',
home: Scaffold(
appBar: AppBar(
title: Text("Demo"),
),
body: SafeArea(
child: IndexedStack(
index: Get.find<NavigationBarController>().tabIndex.value,
children: [
Widget1(),
Widget2()
],
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: Get.find<NavigationBarController>().tabIndex.value,
onTap: Get.find<NavigationBarController>().changeTabIndex,
items: [
_bottomNavigationBarItem(
icon: CupertinoIcons.home,
label: 'Button1',
),
_bottomNavigationBarItem(
icon: CupertinoIcons.rocket_fill,
label: 'Button2',
),
])),
getPages: [
GetPage(
name: '/widget1',
page: () => Widget1(),
binding: Widget1_Bindings(),
),
GetPage(
name: '/widget2',
page: () => Widget2(),
binding: Widget2_Bindings(),
),
],
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.system,
);
}
}
class NavigationBarController extends GetxController {
static NavigationBarController get to => Get.find();
var tabIndex = 0.obs;
void changeTabIndex(int index) {
tabIndex.value = index;
update();
}
@override
void onInit() {
super.onInit();
}
@override
void dispose() {
super.dispose();
}
}
class Controller1 extends GetxController {
var _test2 = "test1".obs;
get test1 => this._test2.value;
}
class Controller2 extends GetxController {
var _test2 = "test2".obs;
get test1 => this._test2.value;
}
class Widget1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Text("Widget1"),
);
}
}
class HomeBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut(() => NavigationBarController());
}
}
class Widget1_Bindings extends Bindings {
@override
void dependencies() {
Get.lazyPut(() => Controller1());
}
}
class Widget2_Bindings extends Bindings {
@override
void dependencies() {
Get.lazyPut(() => Controller2());
}
}
class Widget2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Text("Widget2"),
);
}
}
_bottomNavigationBarItem({required IconData icon, required String label}) {
return BottomNavigationBarItem(
icon: Icon(icon),
label: label,
);
}
第二个问题是我无法弄清如何使得 GetX 路由像Get.to
一样工作。
bindings
何时有用?当我使用单独的屏幕/页面时? - Dmitry Bubnenkovflutter: Null check operator used on a null value
,但我没有使用null check operator(!)...(我的问题与BottomNabBar有关)。 - saddam