Saturday, August 1, 2020

Flutter Navigations

How we can navigate to different screens in your Flutter app.
1. Navigating to a screen. 
2. Navigation using named routes
3. Passing data to a screen
...................................................................................................................................................................................................................
Example : #1 [ Navigating to a Screen Using Material Page Route]
 Navigator.push and Navigator.pop

Code Here
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Homes(),
    );
  }
}

class Homes extends StatefulWidget {
  @override
  _HomesState createState() => _HomesState();
}

class _HomesState extends State<Homes> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.of(context)
                .push(MaterialPageRoute(builder: (_) => Setting()));
     //or
            // Navigator.push(
            //     context, MaterialPageRoute(builder: (_) => Setting()));
          },
          child: Text("Go to Setting"),
        ),
      ),
    );
  }
}

class Setting extends StatefulWidget {
  @override
  _SettingState createState() => _SettingState();
}

class _SettingState extends State<Setting> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Setting"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go to Home'),
        ),
      ),
    );
  }
}



Important: Note that we are pushing a new route to the stack, this will automatically add a back option to the App bar. There’s no need but if you want, you can add a Back button like this

RaisedButton(child: Text('Back'),
onPressed: () {
Navigator.pop(context);
}


Happy Coding ;)
...................................................................................................................................................................................................................
Example : #2 [ Hiding BackButton using pushReplacement ]
what if you need to replace your screen instead of pushing a new screen? Simple, you’ll use pushReplacement() method keeping the arguments same. In this case, pressing the back button of the device will take you out of the app.
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Homes(),
    );
  }
}

class Homes extends StatefulWidget {
  @override
  _HomesState createState() => _HomesState();
}

class _HomesState extends State<Homes> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            // Navigator.of(context)
            //     .pushReplacement(MaterialPageRoute(builder: (_) => Setting()));
      //or
             Navigator.pushReplacement(
                 context, MaterialPageRoute(builder: (_) => Setting()));
          },
          child: Text("Go to Setting"),
        ),
      ),
    );
  }
}

class Setting extends StatefulWidget {
  @override
  _SettingState createState() => _SettingState();
}

class _SettingState extends State<Setting> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Setting"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text("Go to Home"),
        ),
      ),
    );
  }
}

Happy Coding :)
...................................................................................................................................................................................................................
Example : #3 [ Navigation using named routes]

Now we’ll look at how we can achieve the same goal using named routes. Named routes are recommended when you are navigating to a screen from multiple screens.

Notice that named route looks much clearer.
//previous
Navigator.push(context, MaterialPageRoute(builder: (context) => Setting()));
Navigator.of(context)
                 .push(MaterialPageRoute(builder: (_) => Setting()));

Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Setting()));
Navigator.of(context)
                 .pushReplacement(MaterialPageRoute(builder: (_) => Setting()));


//named route
Navigator.pushNamed(context, '/setting');
Navigator.of(context).pushNamed('/setting');
Navigator.of(context).pushReplacementNamed('/setting');
Navigator.pushReplacementNamed(context, '/setting');

Code Here
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
     // home: Homes(),                // Comment it because no longer required
      initialRoute: '/',
      routes: {
        "/": (context) => Homes(), 
        "/setting": (context) => Setting()
        },
    );
  }
}

class Homes extends StatefulWidget {
  @override
  _HomesState createState() => _HomesState();
}

class _HomesState extends State<Homes> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            // Navigator.of(context)
            //     .push(MaterialPageRoute(builder: (_) => Setting()));
            //or

            //  Navigator.push(
            //      context, MaterialPageRoute(builder: (_) => Setting()));

// Name router

            Navigator.pushNamed(context, '/setting');
           // Navigator.pushReplacementNamed(context, '/setting');
          },
          child: Text("Go to Setting"),
        ),
      ),
    );
  }
}

class Setting extends StatefulWidget {
  @override
  _SettingState createState() => _SettingState();
}

class _SettingState extends State<Setting> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Setting"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go to Home'),
        ),
      ),
    );
  }
}

Happy Coding :)
...................................................................................................................................................................................................................
Example : #4 

import 'package:flutter/material.dart';
void main() => {
      runApp(MaterialApp(
        
        initialRoute: "/",
        routes: {
          '/':(context)=>MyApp(),
          '/setting':(context)=>Setting(),
        },
      ))
    };

class MyApp extends StatefulWidget {
  @override  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: () {
                Navigator.pushNamed(context,'/setting');
              },
              child: Text('Navigate to Setting'),
            )
          ],
        ),
      ),
    );
  }
}

class Setting extends StatelessWidget {
  @override  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: () {
                Navigator.pop(context,"/");
              },
              child: Text('Navigate to Home'),
            )
          ],
        ),
      ),
    );
  }
}

Happy Coding :)
...................................................................................................................................................................................................................
Example : #5



Happy Coding :)
...................................................................................................................................................................................................................
Example : #6






Example : #3 [Material Page Route Builder]
slidePageAnimations.dart
import 'package:flutter/material.dart';

class SlidePageAnimations extends PageRouteBuilder {
Widget widget;
SlidePageAnimations({this.widget}):super(
pageBuilder:(context, animation, secondaryAnimation)=>widget,
transitionsBuilder:(context, animation, secondaryAnimation, child){
return SlideTransition(
position: Tween<Offset>(
//left to right
//begin: Offset(-1.0,0.0),
//Top to Bottom
// begin: Offset(0.0,-1.0),
begin: Offset(1.0,1.0),
end: Offset.zero
).animate(animation),
child: SlideTransition(
position: Tween<Offset>(
begin: Offset.zero,
end: Offset(0.0, 1.0),
).animate(secondaryAnimation),
child: child,
),
);

}
);
}
...................
page2.dart
import 'package:flutter/material.dart';

class Page2 extends StatelessWidget{
@override
Widget build(BuildContext context){
return Scaffold(
backgroundColor: Colors.yellow,
appBar: AppBar(
title: Text('Page 2'),
),
body: Center(
child: Text('This is the Page 2 '),
),

);
}
}
..................
home.dart
import 'package:flutter/material.dart';
import 'package:shoppingproject/page2.dart';
import 'package:shoppingproject/routes/pageRouteAnimations.dart';

class Home extends StatefulWidget{
@override
HomeState createState()=>HomeState();
}
class HomeState extends State<Home>{
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text('Homes'),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
Navigator.push(context, SlidePageAnimations(
widget: Page2()
));
},
),
body: Center(
child: Text('This is the Home Page'),
),
);
}
}
.......................
main.dart
import 'package:flutter/material.dart';
import 'package:shoppingproject/home.dart';
void main()=>runApp(MyApp());

class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
home: Home(),
theme: ThemeData(
primarySwatch: Colors.green
),
);
}
}
...................................................................................................................................................................................................................
Example : #4 [Hero]
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final size = 150.0;
    return Scaffold(
      appBar: AppBar(
        title: Text('Main Screen'),
      ),
      body: GestureDetector(
        onTap: () {
          Navigator.of(context).push(PageRouteBuilder(
              transitionsBuilder:
                  (context, animation, secondaryAnimation, child) {
                return child;
              },
              pageBuilder: (context, animation, secondaryAnimation) =>
                  HeroDetails()));
        },
        child: Hero(
          tag: 'myImage',
          child: CircleAvatar(
            radius: 80.0,
            backgroundImage: AssetImage('assets/images/de.jpg'),
          ),
        ),
      ),
    );
  }
}

class HeroDetails extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hero Detial Screen'),
      ),
      body: Center(
        child: Container(
          child: Hero(
            tag: 'myImage',
            child: Image.asset('assets/images/vd.jpg')
          ),
        ),
      ),
    );
  }
}

...................................................................................................................................................................................................................
Example : #5 
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      //home: MyHome(),
      routes: <String, WidgetBuilder>{
        '/': (BuildContext context) => MyHome(),
        '/details': (BuildContext context) => Details(),
      },
    ));

class MyHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('App Bar'),
      ),
      body: GestureDetector(
         onTap: () {
          Navigator.of(context).pushNamed("/details");
        },
        child: CircleAvatar(
        backgroundImage: AssetImage('assets/images/de.jpg'),
        ),
       
      ),
    );
  }
}

class Details extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Details'),
      ),
    );
  }
}
...................................................................................................................................................................................................................
Example : #6 []
import 'package:flutter/material.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //home: Home(),
      initialRoute: "/",
      routes: {
        "/":(contex)=>Home(),
        "setting":(context)=>Setting()
      },
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home.'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Center(
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.only(top: 20),
                decoration: BoxDecoration(   
                  color: Colors.black
                ),
                child: FlatButton( 
                  child: Text('Login and go Settings', style: TextStyle(color: Colors.white),),
                  onPressed: (){
                      Navigator.pushNamed(context, "setting");
                  },
                ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

class Setting extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Setting'),
      ),
      body: Container(
        decoration: BoxDecoration(color: Colors.red),
      ),
    );
  }
}

...................................................................................................................................................................................................................
Example : #7 []

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  Home() : super();
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  void gotoNext(BuildContext context) {
    Navigator.push( context, MaterialPageRoute(  
      builder: (BuildContext context) => Setting(),
    ));
  }

void gotoNext(BuildContext context) { 
 Navigator.of(context).push(MaterialPageRoute(
 builder: (context) => Setting(), )); 
 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(
              child: Text('Go to Setting Screen'),
              onPressed: () {
                gotoNext(context);
              },
            )
          ],
        ),
      ),
    );
  }
}

class Setting extends StatefulWidget {
  Setting() : super();
  @override
  _SettingState createState() => _SettingState();
}

class _SettingState extends State<Setting> {

  void goBack(BuildContext context){
    Navigator.pop(context);
  }
  void goProfile(BuildContext context){
    Navigator.push(context, MaterialPageRoute(
      builder: (BuildContext context) => Profile(),
      ));
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(  
        title: Text('Setting'),
      ),
      body: Center(  
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(  
              child: Text('Go Back'), 
              onPressed: (){
                goBack(context);
              },
            ),
            SizedBox(height: 20.0),
             RaisedButton(  
              child: Text('Go Profile'), 
              onPressed: (){
                goProfile(context);
              },
            )
          ],
        ),
      ),

    );
  }
}


class Profile extends StatefulWidget {
  Profile() : super();
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {

  void goBack(BuildContext context){
    Navigator.pop(context);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(  
        title: Text('Profile'),
      ),
      body: Center(  
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(  
              child: Text('Go Back'), 
              onPressed: (){
                goBack(context);
              },
            )
          ],
        ),
      ),

    );
  }
}

...................................................................................................................................................................................................................
Example : #8 [ Pass Data one Screens to Another Screen]
setting.dart

import 'package:demo1/screens/user.dart';
import 'package:flutter/material.dart';

class Setting extends StatelessWidget {
  final User user;
  Setting({Key key, this.user}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(
        title: Text("Home Page"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context, true);
          },
          child: Text('Logout ${user.username}')
        ),
      ),
    );
  }
}
or ....StatefulWidget

import 'package:demo1/screens/user.dart';
import 'package:flutter/material.dart';

class Setting extends StatefulWidget {
  final User user;
  Setting({Key key, this.user}) : super(key: key);

  @override
  _SettingState createState() => _SettingState();
}

class _SettingState extends State<Setting> {
  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(
        title: Text("Home Page"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context, true);
          },
          child: Text('Logout ${widget.user.username}')
        ),
      ),
    );
  }
}
.......................................
home.dart

import 'package:demo1/screens/setting.dart';
import 'package:demo1/screens/user.dart';
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
  TextEditingController usernameController = TextEditingController();
  TextEditingController emailController = TextEditingController();

 void gotoNext(BuildContext context) async{
   User user = new User(usernameController.text, emailController.text);
   final results = await Navigator.of(context).push(MaterialPageRoute(
     builder: (context)=>Setting(user:user)));
     print(results);

 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(  
        title: Text("Home Screen"),
      ),
      body: Padding(  
        padding: EdgeInsets.all(20),
        child: Center(  
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: usernameController,

              ),
              SizedBox(height: 10),
              TextField(
                controller: emailController,
              ),
              SizedBox(height: 10),
              RaisedButton(  
                child: Text('Login'),
                onPressed: (){
                  gotoNext(context);
                },
              )
            ],
          ) ,
        ),
      ),
    );
  }
}

...............................................

import 'package:demo1/screens/home.dart';
import 'package:flutter/material.dart';
void main()=>runApp(MyApp());

class MyApp extends StatelessWidget{
  @override 
  Widget build(BuildContext context){
    return MaterialApp(
      home: Home(),
    );
  }
}



...................................................................................................................................................................................................................
Example : #9 []



...................................................................................................................................................................................................................
Example : #10 []



No comments:

Post a Comment