To start a flutter project, at first we need to make sure that we have flutter sdk and the editing tools like- Android studio, Visual studio etc.

To download the flutter SDK, at first visit the site-

https://flutter.dev/docs

Click on Get Started-> Select your OS (Windows/ Linux / MacOS)

For Windows, follow the instruction-

After installing the Android studio and setting up all the necessary SDKs we need to install Flutter plugin by following the steps:

Settings -> Plugins -> Search for Flutter -> install Flutter -> Restart Android Studio

After that, we will have the Create Flutter project option. To create a new flutter project follow the steps:

Start a new flutter project -> Select Flutter application -> Next -> Set the project name -> Flutter SDK path -> Project location -> Next -> Select company name -> Finish.

It will auto generate some code and the output of the program will be like below:

 

Now, we will delete the unnecessary codes to start our project from scratch:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(

      ),

    );
  }
}

 

In this code, we need to understand some important topics below:

The difference between Stateless and Stateful widgets:

1. The Stateless widgets are used wrap the designing components which don’t need to update or it’s not dynamic. For example, we want to set a title at top of the screen and it won’t never change, then we will set the Text inside the Stateless Widget.

2. The Stateful widgets are used to wrap the components which are dynamic or changes on basis of some actions performed. For example, if we want to set a counter and update the Text on button click, we need to set that Text inside the Stateful widget.

For more details understanding we can visit the blog like below:

https://flutterdoc.com/stateful-or-stateless-widgets-42a132e529ed

Scaffold: Scaffold is basically the Flutter material designing layout structure. It is declared inside the build function of the Stateful class. It contains almost all designing widgets as its child which are enough a full functionalized app. (For example: we can get AppBar, FloatingActionButton, Bottom Navigation bar, Persistent Footer Buttons etc).

 

Making a Splash Screen:

In the main.dart file, we will specify what we want to show in our splash screen and then, in which page we will go after that.

For that purpose, we need to create SplashScreen class which will extend StatefulWidget. In that class, inside createState we will initialize a StatefulWidget named _SplashScreenState

class SplashScreen extends StatefulWidget {
   
  @override
  _SplashScreenState createState() => new _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {

  startTime() async {
    var _duration = new Duration(seconds: 2);
    return new Timer(_duration, navigationPage);
  }

  void navigationPage() async {
      Navigator.of(context).pushReplacementNamed('/LoginScreen');
  }

  @override
  void initState() {
    super.initState();
    getToken();
    startTime();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Image.asset('images/diamond.png'),
      ),
    );
  }
}

Now, inside the main function we need to call the SplashScreen class.

import 'dart:async';
import 'package:flutter/material.dart';

void main() {

  runApp(new MaterialApp(
    home: new SplashScreen(),
  ));

}

So, our splash screen is ready. It will appear for 2 seconds as we used the duration inside the startTime function like below:

startTime() async {
  var _duration = new Duration(seconds: 2);
  return new Timer(_duration, navigationPage);
}

Setting up the screens for Navigation drawer:

For including my screens in navigation drawer, at first we need to create all the classes attached to the navigation drawer. Suppose, in our navigation drawer we want three items – Home, AllNotes, Settings, Logout we create – three classes HomeFragment, SettingsFragment, AllNotesFragment

Here is a sample of code what should we initially write in those class-

 

import 'package:flutter/material.dart';

class SettingsFragment extends StatefulWidget {
  @override
  _SettingsFragmentState createState() => new _SettingsFragmentState();
}

class _SettingsFragmentState extends State<SettingsFragment> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(

      body: new Center(
        child: new Text('Welcome to Settings.!'),
      ),
    );
  }
}

Now, in the HomeScreen class we set the drawer items in a sequence. Suppose, in each drawer item it contains an icon and a title. For that purpose, we will create one class inside the HomeScreen.dart file-

class DrawerItem {
  String title;
  IconData icon;
  DrawerItem(this.title, this.icon);
}

In the HomePage class which extends the StatefulWidget, at first we will declare an array variable drawerItems with the all Drawer Items name along Icon.

final drawerItems = [
  new DrawerItem("Home Page", Icons.home),
  new DrawerItem("All Notes", Icons.note),
  new DrawerItem("Log Out", Icons.info)
];

Now, inside the HomePageState class that extends State we will declare one initial state-

int _selectedDrawerIndex = 0;

Then we will declare one function _getDrawerItemWdiget(int pos) , we will set which fragments to open for which position.

_getDrawerItemWidget(int pos) {
  switch (pos) {
    case 0:
      return new HomeFragment();
    case 1:
      return new AllNotesFragment();
    case 2:
      return new SettingsFragment();

    default:
      return new Text("Error");
  }
}

To perform onTap actions for some specific index of the drawer items, we will create one _onSelectItem(int index) function like below:

_onSelectItem(int index) {
  setState(() {
    _selectedDrawerIndex = index;

    if(_selectedDrawerIndex == 2) {
      LocalStore().saveJWT(null);
      Navigator.of(context).pushNamedAndRemoveUntil('/LoginScreen', (Route<dynamic> route) => false);
    }

  });
}

Inside the build function, we will show each of the drawer items using ListTile using for loop.

List<Widget> drawerOptions = [];
for (var i = 0; i < widget.drawerItems.length; i++) {
  var d = widget.drawerItems[i];
  drawerOptions.add(
      new ListTile(
        leading: new Icon(d.icon),
        title: new Text(d.title),
        selected: i == _selectedDrawerIndex,
        onTap: () => _onSelectItem(i),
      )
  );
}

Now, in Scaffold we have one drawer option and inside that we will declare our drawer header properties like below:

      drawer: new Drawer(
        child: new Column(

          children: <Widget>[
            Container(
              height: 200.0,
              width: double.infinity,
              color: Colors.red,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Center(
                  child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          CircleAvatar(
                            radius: 40.0,
                            backgroundImage: NetworkImage(
                                "https://randomuser.me/api/portraits/men/1.jpg"
                            ),
                          ),

                          SizedBox(
                            height: 10.0
                          ),

                          Text(
                            "$firstName",
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18
                            ),
                          ),

                          SizedBox(
                              height: 10.0
                          ),

                          Text(
                            "$email",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 16
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),

            new Column(children: drawerOptions)
          ],
        ),
      ),

Then inside the body we will just simply call our _getDrawerWidget function.

Entire code of HomeScreen.dart

class HomePage extends StatefulWidget {
  final drawerItems = [
    new DrawerItem("Home Page", Icons.home),
    new DrawerItem("All Notes", Icons.note),
    new DrawerItem("Log Out", Icons.info)
  ];

  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  int _selectedDrawerIndex = 0;

  _getDrawerItemWidget(int pos) {
    switch (pos) {
case 0:
  return new HomeFragment();
case 1:
  return new AllNotesFragment();
case 2:
  return new SettingsFragment();

default:
  return new Text("Error");
    }
  }

  _onSelectItem(int index) {
    setState(() => _selectedDrawerIndex = index);
    Navigator.of(context).pop(); // close the drawer
  }

  @override
  Widget build(BuildContext context) {
    var drawerOptions = <Widget>[];
    for (var i = 0; i < widget.drawerItems.length; i++) {
      var d = widget.drawerItems[i];
      drawerOptions.add(
          new ListTile(
            leading: new Icon(d.icon),
            title: new Text(d.title),
            selected: i == _selectedDrawerIndex,
            onTap: () => _onSelectItem(i),
          )
      );
    }

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.drawerItems[_selectedDrawerIndex].title),
      ),
      drawer: new Drawer(
        child: new Column(
          children: <Widget>[
            Container(
              height: 200.0,
              width: double.infinity,
              color: Colors.red,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Center(
                  child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          CircleAvatar(
                            radius: 40.0,
                            backgroundImage: NetworkImage(
                                "https://randomuser.me/api/portraits/men/1.jpg"
                            ),
                          ),

                          SizedBox(
                            height: 10.0
                          ),

                          Text(
                            "$firstName",
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18
                            ),
                          ),
                          SizedBox(
                              height: 10.0
                          ),

                          Text(
                            "$email",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 16
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),

            ),

            new Column(children: drawerOptions)
          ],
        ),
      ),
      body: _getDrawerItemWidget(_selectedDrawerIndex),
    );
  }
}

The final output will be something like this-

Previous ArticleNext Article
Android Developer

Leave a Reply

Your email address will not be published. Required fields are marked *