Flutter / GetX Steps / Step3: Page Navigation
Page Navigation (from one screen to another screen)
-
Steps
Read the topics step1 : New project 1. create new controller
// controllers/login_controller.dart import 'package:get/get.dart'; class LoginController extends GetxController { } 2. Create binding
1) create login_binding.dart under lib/bindings folder
// bindings/login_binding.dart import 'package: /controllers/login_controller.dart'; import 'package:get/get.dart'; class LoginBinding extends Bindings { @override void dependencies() { Get.lazyPut(() => LoginController()); } } 1. replace
with your project name in the pubspec.yaml 3. Create view
1) create login_page.dart under lib/views folder
// views/login_page.dart import 'package:flutter/material.dart'; import 'package: /controllers/login_controller.dart'; import 'package:get/get.dart'; class LoginPage extends StatelessWidget { @override Widget build(BuildContext context) { return GetBuilder ( builder: (controller) => Scaffold( appBar: AppBar( title: const Text('Login'), ), body: const Center( child: Text('Hello World!'), ), ), ); } } 1. replace
with your project name in the pubspec.yaml 4. add new route to the existing file lib/reoutes/app_pages.dart
1. import binding file and view file
import 'package: /bindings/login_binding.dart'; import 'package: /views/login_page.dart'; 2. add GetPage for new route
GetPage( name: '/login', page: () => LoginPage(), binding: LoginBinding(), ), Complete code
// reoutes/app_pages.dart import 'package: /bindings/home_binding.dart'; import 'package: /views/home_page.dart'; import 'package: /bindings/login_binding.dart'; import 'package: /views/login_page.dart'; import 'package:get/get.dart'; class AppPages { static final List pages = [ GetPage( name: '/home', page: () => HomePage(), binding: HomeBinding(), ), GetPage( name: '/login', page: () => LoginPage(), binding: LoginBinding(), ), ]; } 5. Add links for the route in the drawer menu
1. add drawer praperty to scaffold(). See previous topics
2. add Get.offNamed() in the onTap: () for navigation when we touch the link
Complete code of Widget build in view page login_page.dart
// views/login_page.dart Widget build(BuildContext context) { return GetBuilder ( builder: (controller) => Scaffold( appBar: AppBar( title: const Text('Login'), ), body: const Center( child: Text('Hello World!'), ), drawer: Drawer( // Add a ListView to the drawer. This ensures the user can scroll // through the options in the drawer if there isn't enough vertical // space to fit everything. child: ListView( // Important: Remove any padding from the ListView. padding: EdgeInsets.zero, children: [ const DrawerHeader( decoration: BoxDecoration( color: Colors.blue, ), child: Text('Drawer Header'), ), ListTile( title: const Text('Home'), onTap: () { Get.offNamed('/home'); }, ), ListTile( title: const Text('Login'), onTap: () { Get.offNamed('/login'); }, ), ], ), ), ), ); }