Flutter – AppDividend https://appdividend.com Latest Code Tutorials Wed, 12 Dec 2018 10:36:47 +0000 en-US hourly 1 https://wordpress.org/?v=5.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Flutter – AppDividend https://appdividend.com 32 32 Flutter Tabs Tutorial | Working with Tabs Example https://appdividend.com/2019/01/20/flutter-tabs-tutorial-working-with-tabs-example/ https://appdividend.com/2019/01/20/flutter-tabs-tutorial-working-with-tabs-example/#comments Sun, 20 Jan 2019 17:44:07 +0000 http://localhost/wordpress/?p=3663 Flutter Tabs Tutorial With Example

Flutter Tabs Tutorial | Working with Tabs Example is today’s topic. Working with tabs is a typical pattern in Android and iOS apps following the Material Design guidelines.  Flutter includes a very convenient way to create tab layouts. For tabs to work, we will need to keep the selected tab and content sections in sync. It is […]

The post Flutter Tabs Tutorial | Working with Tabs Example appeared first on AppDividend.

]]>
Flutter Tabs Tutorial With Example

Flutter Tabs Tutorial | Working with Tabs Example is today’s topic. Working with tabs is a typical pattern in Android and iOS apps following the Material Design guidelines. 

Flutter includes a very convenient way to create tab layouts. For tabs to work, we will need to keep the selected tab and content sections in sync. It is the job of the TabController.  Our example app has a screen which contains a tab bar with two screens.

To add Tabs to the app, all I needed was to create TabBar and TabBarView and attach TabController to them. TabController will sync TabBar with TabBarView so we can have behavior we wanted.

Flutter Tabs Tutorial With Example

Using the DefaultTabController is the simplest option since it will create the TabController for us and make it available to all descendant Widgets. The syntax of DefaultTabController is following.

DefaultTabController(
  // The number of tabs / content sections we need to display
  length: 3,
  child: // See the next step!
);

Step 1: Install the Flutter App.

If you are new to flutter and do not know how to install flutter on the mac, then check out this article.

After that, if you do not know how to write a widget in the flutter, then please go to this link.

Step 2: Create two screens.

Inside the lib folder, create one folder called screens and inside that create two files.

  1. FirstScreen.dart
  2. SecondScreen.dart

Write the following code inside the FirstScreen.dart.

// FirstScreen.dart

import 'package:flutter/material.dart';

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Text('Tab 1 Layout'),
      ),
    );
  }
}

In the above code, we have just added one centered text.

When the user clicks on the first tab button, we will see this screen.

Write the following code inside the SecondScreen.dart.

// SecondScreen.dart

import 'package:flutter/material.dart';

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Text('Tab 2 Layout'),
      ),
    );
  }
}

This is the second tab layout. So we have created the two tab layouts for our application.

Now, the remaining thing is to create a DefaultTabController

Step 3: Create a DefaultTabController

Write the following code inside the main.dart file.

// main.dart

import 'package:flutter/material.dart';

import './pages/FirstScreen.dart';
import './pages/SecondScreen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit))
              ],
            ),
            title: Text('Flutter Tabs Example'),
          ),
          body: TabBarView(
            children: [
              FirstScreen(),
              SecondScreen(),
            ],
          ),
        ),
      ),
    );
  }
}

In the above code, we have imported two screens which are created earlier in this article.

Our application has only two tabs. So, we have assigned a length to two.

Then, we have taken the TabBar and assigned two tab icons.

Now, let’s define the TabBarView which have two screens. So when the user clicks on one of the icons, it will display the associated the Screens.

Save the file and go to the terminal and type the following command. Please make sure that both iOS and Android Simulators are open. We will check the output on both the Virtual Devices.

flutter run -d all

See the output below.

 

Flutter Tabs Tutorial | Working with Tabs Example

Above app is the basic Flutter Tabs Example, but you understand how we can build a Tab based layout in Flutter Application. Finally, Flutter Tabs Tutorial | Working with Tabs Example is over.

The post Flutter Tabs Tutorial | Working with Tabs Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/20/flutter-tabs-tutorial-working-with-tabs-example/feed/ 3
Python List Extend Example | extend() Method Tutorial https://appdividend.com/2019/01/04/python-list-extend-example-tutorial/ https://appdividend.com/2019/01/04/python-list-extend-example-tutorial/#respond Fri, 04 Jan 2019 11:45:00 +0000 http://localhost/wordpress/?p=3066 Python List extend() Method Example | Python Standard Libary Tutorial

Python List Extend Example | extend() Method Tutorial is today’s topic. Python extend() method adds the specified list elements (or any iterable) to the end of the current list.  The extend() extends the list by adding all items of the list (passed as an argument) to an end. Python List Extend Example The syntax for python […]

The post Python List Extend Example | extend() Method Tutorial appeared first on AppDividend.

]]>
Python List extend() Method Example | Python Standard Libary Tutorial

Python List Extend Example | extend() Method Tutorial is today’s topic. Python extend() method adds the specified list elements (or any iterable) to the end of the current list.  The extend() extends the list by adding all items of the list (passed as an argument) to an end.

Python List Extend Example

The syntax for python list extend() method is following.

list.extend(iterable)

An iterable parameter is required, and it is iterable like set, tuple, list. The extend() method does not return any value but add the content to the existing list.

Let us take an example. My current version of Python is 3.

# app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
Friends = ['Rachel', 'Monica', 'Phoebe']
GoT.extend(Friends)
print(GoT)

Run the file.

python3 app.py

 

Python List Extend Example | extend() Method Tutorial

So, we have added one list to the other, and the output will be six items of the list. It is entirely different behavior then python list append() method example. In that case, we have only four elements, and the 4th one is added as a whole item. So, if you kind of merge to lists then list extend() method is beneficial.

Add Elements of Tuple To List

Let us extend a tuple to the list.

# app.py

GoT1_list = ['Daenerys', 'Jon', 'Tyrion']
Friends1_tuple = ('Rachel', 'Monica', 'Phoebe')
GoT1_list.extend(Friends1_tuple)
print(GoT1_list)

In the above example, we have taken one list and one tuple. Now, we try to add the tuple to a list. The output is following. It will become a single list.

 

Add Elements of Tuple To List

Add Elements of Set To List

Now, we take a Set and add to the List.

# app.py

MJSongs_list = ['Dangerous', 'Smooth criminal', 'Bad']
DrakeSongs_set = {'In my feelings', 'Mia'}
MJSongs_list.extend(DrakeSongs_set)
print(MJSongs_list)

 

 

Add Elements of Set To List

It becomes one list and includes all the elements in a single list. 

The Python native datatypes like tuple and set passed to extend() method is automatically converted to a list. And, the items of the list are appended to the end.

Finally, Python List Extend Example | extend() Method Tutorial is over.

The post Python List Extend Example | extend() Method Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/04/python-list-extend-example-tutorial/feed/ 0
Python List append() Method Example | Python Standard Libary https://appdividend.com/2019/01/04/python-list-append-method-example-tutorial/ https://appdividend.com/2019/01/04/python-list-append-method-example-tutorial/#respond Fri, 04 Jan 2019 10:29:00 +0000 http://localhost/wordpress/?p=3057 Python List append() Method Example | Python Standard Libary Tutorial

Python List append() Method Example | Python Standard Libary is today’s topic. Python has a great built-in list type named “list.” List literals are written within square brackets [ ]. Lists work similarly to strings, use the len() function and square brackets [ ] to access data, with the first element at index 0. The append() method […]

The post Python List append() Method Example | Python Standard Libary appeared first on AppDividend.

]]>
Python List append() Method Example | Python Standard Libary Tutorial

Python List append() Method Example | Python Standard Libary is today’s topic. Python has a great built-in list type named “list.” List literals are written within square brackets [ ]. Lists work similarly to strings, use the len() function and square brackets [ ] to access data, with the first element at index 0. The append() method in Python appends an element or item to the end of the list. The list append() method adds a single element to the existing list. It doesn’t return a new list; instead, it modifies the original list.

Python List append() Method Example

The syntax of append() method is following.

list.append(item)

append() Parameters

The list append() method takes a single element and adds it to the end of the list. An element can be numbers, strings, another list, dictionary, etc.

Adding Element to a List in Python

Let us create a file called app.py and add the following code inside it.

// app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
Friends = 'Rachel'

GoT.append(Friends)
print(GoT)

Save the file and go to the cmd or terminal and run the file using the following command.

python3 app.py

 

Python List append() Method Example | Python Standard Libary

Adding List to a List in Python

Now, write the following code inside the app.py file.

GoT = ['Daenerys', 'Jon', 'Tyrion']
Friends = ['Rachel', 'Monica', 'Phoebe']

GoT.append(Friends)
print(GoT)

In the above example, we are adding a list to the list. So the second list considers as a single list item and it appends as a separate item. The output is following.

 

Adding List to a List in Python

Again, it does not return a new list, modifies the original.

Finally, Python List append() Method Example | Python Standard Libary Tutorial is over.

The post Python List append() Method Example | Python Standard Libary appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/04/python-list-append-method-example-tutorial/feed/ 0
Javascript Promise Reject Example | Promise.reject() Tutorial https://appdividend.com/2019/01/03/javascript-promise-reject-example-tutorial/ https://appdividend.com/2019/01/03/javascript-promise-reject-example-tutorial/#respond Thu, 03 Jan 2019 17:03:09 +0000 http://localhost/wordpress/?p=3048 Javascript Promise.reject() example tutorial

Javascript Promise Reject Example | Promise.reject() Tutorial is today’s topic. The Promise.reject() method returns the Promise object that is rejected with a given reason. The static Promise.reject() function returns the Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error. Javascript Promise Reject Example The syntax for Javascript Promise.reject() method is following. Promise.reject(reason); The […]

The post Javascript Promise Reject Example | Promise.reject() Tutorial appeared first on AppDividend.

]]>
Javascript Promise.reject() example tutorial

Javascript Promise Reject Example | Promise.reject() Tutorial is today’s topic. The Promise.reject() method returns the Promise object that is rejected with a given reason. The static Promise.reject() function returns the Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error.

Javascript Promise Reject Example

The syntax for Javascript Promise.reject() method is following.

Promise.reject(reason);

The parameter reason is why this promise rejected.

Let us take a simple example.

// app.js

const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		reject('fail promise');
	}, 1000);
});

p1.catch(error => { 
	console.log(error);
});

Here, we are rejecting the promise, and then we call the catch method on that promise to catch the error and log that error in the console.

The output is following.

 

Javascript Promise Reject Example | Promise.reject() Tutorial

We can also debug the error, if throw an instanceof Error object. Take a look at the following code.

// app.js

const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		reject(new Error('Promise failed'));
	}, 1000);
});

p1.then(error => { 
	console.log(error);
});

The output is following.

 

Promise.reject() Tutorial

Here, we are getting the detailed Error Stack Trace.

Finally, Javascript Promise Reject Example | Promise.reject() Tutorial is over.

The post Javascript Promise Reject Example | Promise.reject() Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/03/javascript-promise-reject-example-tutorial/feed/ 0
Flutter Navigation Example | Navigate To A New Screen And Back Tutorial https://appdividend.com/2019/01/02/flutter-navigation-example-tutorial/ https://appdividend.com/2019/01/02/flutter-navigation-example-tutorial/#comments Wed, 02 Jan 2019 12:32:41 +0000 http://localhost/wordpress/?p=3012 Flutter Navigation Tutorial With Example From Scratch

Flutter Navigation Example | Navigate To A New Screen And Back Tutorial is today’s topic.  In Android terms, our screens would have new Activities. In iOS terms, we have new ViewControllers. In Flutter, screens are just Widgets! So how do we navigate to new screens? the answer is using the Navigator class!  Navigation is the key part of […]

The post Flutter Navigation Example | Navigate To A New Screen And Back Tutorial appeared first on AppDividend.

]]>
Flutter Navigation Tutorial With Example From Scratch

Flutter Navigation Example | Navigate To A New Screen And Back Tutorial is today’s topic.  In Android terms, our screens would have new Activities. In iOS terms, we have new ViewControllers. In Flutter, screens are just Widgets! So how do we navigate to new screens? the answer is using the Navigator class! 

Navigation is the key part of the UX for any mobile application. Due to the limited screen on mobile devices, users will always be navigating between different screens, for example, from a list to a detail screen, from the shopping cart to the checkout screen, from the menu into a form, and many other cases. Good navigation helps users find their way around and get the sense of the breadth of your app.

The iOS navigation experience is often built-around the UINavigationController, which uses the stack-based approach to shifting between screens. On Android, an Activity stack is the central means to navigate the user between different screens. Unique transitions between screens in these stacks can help give your app a unique feel.

Flutter Navigation Example Tutorial

A multi-page application is one where we create multiple screens with their widgets with one of them being displayed at any point in time. Most of the time, the screens are displayed based on user interactions with the app, which is achieved using navigation functionalities.

Navigator class

It is the widget that manages a set of child widgets with a stack discipline. Mobile apps typically reveal their contents via full-screen elements called “screens” or “pages.” In Flutter, these elements are called routes, and they’re managed by a Navigator widget. The navigator leads a stack of Route objects and provides methods for controlling the stack, like Navigator.push and Navigator.pop.

Navigator.push

It pushes the given route onto the navigator that most tightly encloses the given context. The syntax is following.

Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => MyPage()));

Navigator.pop

It pops the top-most route off the navigator that most tightly encloses the given context. The syntax is following.

Navigator.pop(context);

Let us take a simple example to see Flutter Navigation Example in action.

Step 1: Create a Flutter project.

If you do not know how to create a brand new flutter project, then please check out my How To Install Flutter article, we can create a new project from Visual Studio Code.

Now, create one folder inside the lib folder called pages and create two screens inside that folder.

  1. HomeScreen.dart
  2. SecondScreen.dart

Step 2: Code the SecondScreen.dart file.

Write the following code inside the SecondScreen.dart file. Here, I am going to explain the reverse flow of this demo. So first we are coding the SecondScreen.dart file. Bare with me, and you will understand the flow of this project.

// SecondScreen.dart

import 'package:flutter/material.dart';

class SecondScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Back To HomeScreen'),
          color: Theme.of(context).primaryColor,
          textColor: Colors.white,
          onPressed: () => Navigator.pop(context)
        ),
      ),
    );
  }
}

In this page, we have taken the StatelessWidget because we do not need the StatefulWidget cause no data here to be managed.

This is our SecondScreen, and here, when the user presses the button, we will go to one step back of the screen. We pop the route from the stack and get back to the previous route.

In our case, it is a HomeScreen.dart page that we will navigate after we click the Back To HomeScreen button. So let us code that file.

Step 3: Code the HomeScreen.dart file.

Write the following code inside the HomeScreen.dart file.

// HomeScreen.dart

import 'package:flutter/material.dart';

import './SecondScreen.dart';

class HomeScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Screen'),
      ),
      body: Center(
          child: RaisedButton(
              child: Text('Go to Second Screen'),
              color: Theme.of(context).primaryColor,
              textColor: Colors.white,
              onPressed: () => Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (BuildContext context) => SecondScreen(),
                  )))),
    );
  }
}

This is our HomeScreen, and the first screen appears when the app is compiled.

This screen is also the Stateless Widget because we do not have any state to manage. Now, here also, we have taken the RaisedButton widget.

When the user clicks that button, we are calling the Navigator.push() method and pass the context and MaterialPageRoute parameters.

The MaterialPageRoute() widget also takes one function argument called the builder, and in that argument, we need to pass our destination page to which we need to navigate. In our case, it is a second screen, so we have created an instance of SecondScreen, and we have also imported that screen at the top of the file.

So, when the user clicks on the Go to second screen button, we will navigate to the SecondScreen, and when the user clicks the SecondScreen’s button, we will navigate to this screen which is HomeScreen.

The final step is to code the main.dart file.

// main.dart

import 'package:flutter/material.dart';

import './pages/HomeScreen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(primarySwatch: Colors.deepPurple), home: HomeScreen());
  }
}

We are setting the first screen of the App as a HomeScreen. So we are importing the HomeScreen.dart file inside the main.dart file and pass that instance to the home property, and now we can see the HomeScreen as a first screen of the app.

Open both iOS and Android Simulators and start the compilation using the following command.

flutter run -d all

You can see the HomeScreen like this.

 

Flutter Navigation Example | Navigate To A New Screen And Back Tutorial

Click on the button, and you can see the SecondScreen like this.

 

Flutter Navigation Example Tutorial

Finally, Flutter Navigation Example Tutorial is over. Thanks for taking.

The post Flutter Navigation Example | Navigate To A New Screen And Back Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/02/flutter-navigation-example-tutorial/feed/ 1
Flutter ListView Example | Displaying Dynamic Contents Tutorial https://appdividend.com/2019/01/01/flutter-listview-example-displaying-dynamic-contents-tutorial/ https://appdividend.com/2019/01/01/flutter-listview-example-displaying-dynamic-contents-tutorial/#comments Tue, 01 Jan 2019 18:55:25 +0000 http://localhost/wordpress/?p=2988 ListView.builder tutorial with example

In this tutorial, we will see Flutter ListView Example | Displaying Dynamic Contents. Flutter is the mobile App SDK by Google which helps in creating modern mobile apps for iOS and Android using the single code base. It’s the new entrant in the cross-platform mobile application development, and unlike other frameworks like React Native, it doesn’t use JavaScript but Dart […]

The post Flutter ListView Example | Displaying Dynamic Contents Tutorial appeared first on AppDividend.

]]>
ListView.builder tutorial with example

In this tutorial, we will see Flutter ListView Example | Displaying Dynamic Contents. Flutter is the mobile App SDK by Google which helps in creating modern mobile apps for iOS and Android using the single code base. It’s the new entrant in the cross-platform mobile application development, and unlike other frameworks like React Native, it doesn’t use JavaScript but Dart as the Programming Language.

If you don’t know how to install Flutter, then check out my How To Install Flutter article.  In the real-world apps, dynamic contents are always there and, it is fetched from a backend. So, we need to display those contents in such a way that it does not annoy the user while scrolling down the page.

In this tutorial, we will create a button widget, and when the button is pressed, it will add an item to the List and display that List on the mobile screen. So, when the button is pressed, the state of the widget will change, and the UI will be re-rendered, and we will see the products list inside the mobile screen.

If the length of the item will be increased and reach the limit where we need to scroll down the page, we need to display the scrollbar so that user can quickly scroll down the page. If we do not use ListView, then it will throw a warning in yellow line to indicate that we need to use some widget to show the proper user content and that is why we will use the ListView widget of flutter.

Flutter ListView Example

The standard ListView constructor works well for small lists. If we want to work with lists that contain the large number of items, it’s best to use the ListView.builder constructor.

The main difference between ListView and ListView.builder is that the default ListView constructor requires us to create all items at once whereas the ListView.builder constructor will create items as they are scrolled onto the screen like on demand.

We will use ListView.builder constructor for displaying the items. Let us create a new app in the Visual Studio Code.

Step 1: Create a new flutter project

Go to the VSCode and hit the shortcut keys: cmd + shift + p and type the flutter and it will show to create a new project option, and it creates a new flutter project in your specified folder.

Also, create one folder called assets in the root of the project, we will copy one image to that folder to display inside the Flutter app.

Now, we are going to show an image from the local folder. So, we need to add an image inside pubspec.yaml file.

Add the following line of code inside the pubspec.yaml file.

assets:
    - assets/macbook.jpg

There is already commented line by default by flutter; you need to uncomment it and replace the first line with the assets/your image file with extension.

If you still do not know how to display the image inside the Flutter app then check out How To Display Image in Flutter.

Step 2: Write the Stateful Widget

Now, if you do not know how to write the Stateful Widget in Flutter then check out my this article.

Write the following code inside the main.dart file.

// main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  List<String> _products = ['Laptop'];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      home: Scaffold(
        appBar: AppBar(title: Text('Long List App')),
        body: Column(children: [
          Container(
              margin: EdgeInsets.all(10.0),
              child: RaisedButton(
                  color: Theme.of(context).primaryColor,
                  splashColor: Colors.blueGrey,
                  textColor: Colors.white,
                  onPressed: () {
                    setState(() {
                      _products.add('Macbook');
                    });
                  },
                  child: Text('Add Laptops'))),
          Column(
              children: _products
                  .map((element) => Card(
                        child: Column(
                          children: <Widget>[
                            Image.asset('assets/macbook.jpg'),
                            Text(element,
                                style: TextStyle(color: Colors.deepPurple))
                          ],
                        ),
                      ))
                  .toList()),
        ]),
      ),
    );
  }
}

First, we have created a stateful widget and then set up the theme for the flutter application. Then we have taken one Raised Button, and when the user presses the button, we will add the laptop to the array and display that with the help Card Widget.

We are displaying the two items.

  1. Image
  2. Text

Now, save a file and go to the terminal and type the following command.

flutter run -d all

Make sure; you have opened the iOS Simulator and Android Emulator. After the compilation process, you will see something like this.

Flutter ListView Example | Displaying Dynamic Contents Tutorial

 

Now, click on the Add Laptops button and you will see we can see the second item added into an array.

Now, try to add two or more items, you will see the yellow warning like below.

 

Displaying Dynamic Contents Tutorial

To resolve this problem, we need a ListView.builder() Widget and let us that widget.

Step 3: Add ListView.builder() widget

Let us understand the ListView.builder() widget.

ListView.builder constructor

It creates the scrollable, linear array of widgets that are created on demand.

ListView.builder() constructor is appropriate for list views with ahe large (or infinite) number of children because the builder is called only for those children that are visible.

Providing the non-null itemCount improves the ability of the ListView to estimate the maximum scroll extent.

The itemBuilder callback will be called only with indices greater than or equal to zero and less than itemCount.

Next step is, we will split our codebase into two files.

  1. products.dart
  2. main.dart

The products.dart file only responsible for displaying the items in card widget with the help of ListView.builder constructor widget.

Create one file called products.dart inside the lib folder and add the following code.

// products.dart

import 'package:flutter/material.dart';

class Products extends StatelessWidget {
  final List<String> products;
  Products(this.products);

  Widget _buildProductItem(BuildContext context, int index) {
    return Card(
      child: Column(
        children: <Widget>[
          Image.asset('assets/macbook.jpg'),
          Text(products[index], style: TextStyle(color: Colors.deepPurple))
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: _buildProductItem,
      itemCount: products.length,
    );
  }
}

So, this is the Products class, which has one method called _buildProductItem. This function returns the ListView.builder widget.

ListView.builder widget takes two arguments. One is a function which returns the Widget and second is itemCount which is the length of an array of products.

Now, import this products.dart file inside the main.dart file.

// main.dart

import 'package:flutter/material.dart';

import './products.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  List<String> _products = [];

  @override
  void initState() {
    super.initState();
    _products.add('Laptop');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(primarySwatch: Colors.deepPurple),
        home: Scaffold(
            appBar: AppBar(title: Text('Long List App')),
            body: Column(children: [
              Container(
                  margin: EdgeInsets.all(10.0),
                  child: RaisedButton(
                      color: Theme.of(context).primaryColor,
                      splashColor: Colors.blueGrey,
                      textColor: Colors.white,
                      onPressed: () {
                        setState(() {
                          _products.add('Laptop');
                        });
                      },
                      child: Text('MacBook'))),
              Expanded(child: Products(_products))
            ])));
  }
}

Here, we have used the Expanded widget. It allows us expands a child of a RowColumn, or Flex. Using an Expanded widget makes the child of a RowColumn, or Flex expand to fill the available space in the primary axis (e.g., horizontally for a Row or vertically for a Column). If multiple children are expanded, an available space is divided among them according to the flex factor.

Here, we have passed the imported Products constructor with the argument of the _products array.

Save the file and restart the compilation using the shortcut key and now, add the more than 3 products and see that we are now getting the perfect scrollable view and it will display the product on demand.

This is the most efficient way to display a long list with the ListView by not exactly using ListView but using ListView.builder() constructor.

ListView.builder() Widget Example

 

Finally, Flutter ListView Example | Displaying Dynamic Contents Tutorial is over.

The post Flutter ListView Example | Displaying Dynamic Contents Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/01/flutter-listview-example-displaying-dynamic-contents-tutorial/feed/ 2
How To Create Stateful Widget In Flutter https://appdividend.com/2018/12/16/how-to-create-stateful-widget-in-flutter/ https://appdividend.com/2018/12/16/how-to-create-stateful-widget-in-flutter/#respond Sun, 16 Dec 2018 20:16:58 +0000 http://localhost/wordpress/?p=2570 StatefulWidget In Flutter with an example

In this tutorial, we will see How To Create Stateful Widget In Flutter. Stateful Widget means a widget that has a mutable state. The state is information that can be read synchronously when the widget is built and might change during a lifetime of a widget. It is the responsibility of the widget implementer to ensure that the State is […]

The post How To Create Stateful Widget In Flutter appeared first on AppDividend.

]]>
StatefulWidget In Flutter with an example

In this tutorial, we will see How To Create Stateful Widget In Flutter. Stateful Widget means a widget that has a mutable state. The state is information that can be read synchronously when the widget is built and might change during a lifetime of a widget. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes, using the State.setState method. The stateful widget is the widget that describes part of a user interface by building a constellation of other widgets that represent a user interface more concretely. The building process continues recursively until a description of a user interface is sufficiently concrete.

In this tutorial, we will create a button widget, and when the button is pressed, it will add an item to the List and display that List on the mobile screen. So, when the button is pressed, the state of the widget will change, and the UI will be re-rendered, and we will see the products list inside the mobile screen.

Now, if you do not know how to install flutter on the mac, then you can check out my this article. It will walk you through installing flutter app and opening an app on both Android and iOS simulators.

How To Create Stateful Widget In Flutter

After creating a new project, your project structure looks like this. Remember,  I am using Flutter version 1.0. So, if you have a different structure, then please check the version of your project.

 

How To Create Stateful Widget In Flutter

We will change only one file for this example, and it is lib >> main.dart file.

Skeleton of Stateful Widget

The following is the basic syntax of any Stateful Widget class.

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFFFFE306));
  }
}

So, here first, we have declared our main class called MyApp which extends the StatefulWidget class. That means now we have to define the generic method called createState() in that class.

Now, that method will return one another class which extends the State.

In our case, it is the _MyState class which extends the State. So all the coding related to state updation is inside this class.

createState method

It creates the mutable state for that widget at a given location in the tree. It is implemented by the following code.

@protected
State createState();

Example of Stateful Widget

We are taking one example in which, we will add a button and a card. The card consists of one widget called Text. So when a user clicks on a button, it will add a new item to the list. So the state of the list is changed, and flutter will update its UI, and we will see the lists on the mobile screen.

Now, replace the following code to an existing code inside the lib >> main.dart file.

// main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  List<String> _products = ['Laptop'];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('First app')),
        body: Column(children: [
          Container(
              margin: EdgeInsets.all(10.0),
              child: RaisedButton(
                  onPressed: () {
                    setState(() {
                      _products.add('PC');
                    });
                  },
                  child: Text('Hello World'))),
          Column(
              children: _products
                  .map((element) => Card(
                        child: Column(
                          children: <Widget>[
                            Text(element)
                          ],
                        ),
                      ))
                  .toList()),
        ]),
      ),
    );
  }
}

The List datatype is equivalent to an Array of the Javascript language. You can add, remove the items from the List.

Inside the _MyApp class, we have initialized one list called _products with one item called Laptop. So that is our state variable for this demo.

Now, when a user clicks on a button, it will call the setState() method, which will add the new item on the List and due to change in state, the flutter updates the UI, and we are iterating a card widget based on the list and see the text on the screen.

 

How to add data in flutter list example tutorial

When a user clicks on a button, we will see that PC item will be added every time on the list and you can display that item as a form of a card on the screen.

So, this is how you can work with StatefulWidget in the flutter.

Here, How To Create Stateful Widget In Flutter Tutorial With Example article is over.

The post How To Create Stateful Widget In Flutter appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/16/how-to-create-stateful-widget-in-flutter/feed/ 0
How To Display Image in Flutter https://appdividend.com/2018/12/12/how-to-display-image-in-flutter/ https://appdividend.com/2018/12/12/how-to-display-image-in-flutter/#comments Wed, 12 Dec 2018 10:34:06 +0000 http://localhost/wordpress/?p=2534 Display Static Image In Flutter

In this tutorial, we will see How To Display Image in Flutter. We use Image widget to display the image, and the supported formats are JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP, and WBMP. We mainly use particular Image.asset constructor to display the image. Image.asset Constructor Creates a widget that displays an ImageStream obtained from the asset […]

The post How To Display Image in Flutter appeared first on AppDividend.

]]>
Display Static Image In Flutter

In this tutorial, we will see How To Display Image in Flutter. We use Image widget to display the image, and the supported formats are JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP, and WBMP. We mainly use particular Image.asset constructor to display the image.

Image.asset Constructor

Creates a widget that displays an ImageStream obtained from the asset bundle. The key to the image is given by the name argument. The package argument must be non-null when displaying an image from the package and null otherwise.

How To Display Image in Flutter

The first step is, we need to create a new folder inside the flutter project root called assets. You can name it that folder anything you want but for this demo let us stick it with assets. Inside that folder, add one image manually. In my case it is Krunal.jpg. Remember, we are displaying the static image in the Flutter application.

Now, update the pubspec.yaml file.

Inside the yaml file, you can remove the comment on this part.

assets:
    - assets/Krunal.jpg

So, we are telling flutter explicitly that we are using the static image in the flutter application.

Now, the last step is to replace the following code inside the lib >> main.dart file.

// main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('First app')),
        body: Column(
            children: <Widget>[
              Image.asset(
                'assets/Krunal.jpg',
              ),
              Text('Me')
            ],
          ),
      ),
    );
  }
}

So, here what we have done is that we have taken mainly six widgets. First is our scaffold means the home screen and then inside that we have taken an appbar and body widget which has two children. One is Image, and one is Text.

Image.asset has given one argument that is name to that image and Text widget has the string in its argument, and that is it. Save the file and go to the terminal and start the app.

flutter run -d all

You will see something like this. Of course, your image will be different than mine.

 

How To Display Image in Flutter

So, our How To Display Image in Flutter Tutorial is over.

The post How To Display Image in Flutter appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/12/how-to-display-image-in-flutter/feed/ 1
How To Write A Widget In Flutter https://appdividend.com/2018/12/11/how-to-write-a-widget-in-flutter/ https://appdividend.com/2018/12/11/how-to-write-a-widget-in-flutter/#respond Tue, 11 Dec 2018 16:22:36 +0000 http://localhost/wordpress/?p=2524 Create a stateless widget in flutter

In this tutorial, we will see How To Write A Widget In Flutter. Flutter widgets are built using a modern react-style framework, which takes inspiration from React. The central idea is that you create your UI out of widgets. Widgets describe what their view should look like given their current configuration and state. When a widget’s state changes, […]

The post How To Write A Widget In Flutter appeared first on AppDividend.

]]>
Create a stateless widget in flutter

In this tutorial, we will see How To Write A Widget In Flutter. Flutter widgets are built using a modern react-style framework, which takes inspiration from React. The central idea is that you create your UI out of widgets. Widgets describe what their view should look like given their current configuration and state. When a widget’s state changes, the widget rebuilds its description, which the framework diffs against the previous description to determine the minimal changes needed in the underlying render tree to transition from one state to the next.

Types of Widgets in Flutter

There are mainly two types of Widgets in Flutter.

  1. StatelessWidget Class
  2. StatefulWidget Class

StatelessWidget Class

It is a widget that does not require the mutable state. The stateless widget is a widget that describes the part of a user interface by building a constellation of other widgets that represent the user interface more concretely. The stateless widget is useful when a part of a user interface you are describing does not depend on anything other than the configuration information in an object itself and the BuildContext in which the widget is inflated.

StatefulWidget Class

It is the widget that has mutable state. The stateful widget is a widget that describes part of a user interface by building the constellation of other widgets that describe the user interface more concretely. The Stateful widgets are useful when a part of a user interface you are describing can change dynamically, e.g., due to having an internal clock-driven state, or depending on some system state. So this kind of widget is totally dependent of the State of the widget. If the state changes then it will change the UI according to it.

For compositions that depend only on configuration information in an object itself and the BuildContext in which the widget is inflated, consider using StatelessWidget.

How To Write A Widget In Flutter

If you do not know how to install Flutter on the mac, then please go to this article. Now, we have created a new project. The main file we will going to edit is lib >> main.dart file.

Replace that file with the following code.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('First app')),
        body: Center(
          child: Text('Hello World'),
        ),
      ),
    );
  }
}

Save a file and go to the terminal. Please open both the Android and iOS Simulators. Type the following command.

flutter run -d all

Now, you will see something like this.

 

How To Write A Widget In Flutter

It is entirely Stateless Widget.

Explanation

First, we have imported the material.dart library.

Then define a class called MyApp that extends StatelessWidget. This is a simple widget, and we are displaying just child widgets in this widget like home, appbar, and body.

The home widget is the default route of the flutter application. This is the route that is displayed first when the application is started usually unless initialRoute is specified. It’s also the route that’s displayed if the initialRoute can’t be displayed.

Then appbar widget is an app bar consists of a toolbar and potentially other widgets, such as a TabBar and a FlexibleSpaceBar.  You can compare this as a navbar of bootstrap.

Body is the primary content of the scaffold. The widget in the body of the scaffold is positioned at the top-left of the available space between the app bar and the bottom of the scaffold.

The runApp() function takes the given MyApp Widget and makes it the root of the widget tree. In this example, the widget tree consists of four widgets, the home widget, and its children, the appbar widget and body and body widget’s child the child widget.

So, this is how we can create a widget. Finally, How To Write A Widget In Flutter tutorial is over.

The post How To Write A Widget In Flutter appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/11/how-to-write-a-widget-in-flutter/feed/ 0
How To Install Flutter On Mac https://appdividend.com/2018/12/10/how-to-install-flutter-on-mac/ https://appdividend.com/2018/12/10/how-to-install-flutter-on-mac/#comments Mon, 10 Dec 2018 16:28:12 +0000 http://localhost/wordpress/?p=2508 Flutter For iOS and Android Projects

In this tutorial, we will see How To Install Flutter On Mac.  Flutter allows us to make build beautiful native apps on iOS and Android from the single codebase. Flutter’s widgets architecture incorporates all the critical platform differences such as scrolling, navigation, icons and fonts to provide full native performance on both iOS and Android devices. Flutter’s hot reload helps […]

The post How To Install Flutter On Mac appeared first on AppDividend.

]]>
Flutter For iOS and Android Projects

In this tutorial, we will see How To Install Flutter On Mac.  Flutter allows us to make build beautiful native apps on iOS and Android from the single codebase. Flutter’s widgets architecture incorporates all the critical platform differences such as scrolling, navigation, icons and fonts to provide full native performance on both iOS and Android devices. Flutter’s hot reload helps us quickly and easily experiment, build UIs, add features, and fix bugs faster. Experience sub-second reload times, without losing the state, on emulators, simulators, and hardware for iOS and Android. Delight your users with Flutter’s built-in beautiful Material Design and Cupertino (iOS-flavor) widgets, rich motion APIs, smooth, natural scrolling, and platform awareness.

We are using Flutter 1.0 for this installation demo. So let us see How To Install Flutter On Mac.

How To Install Flutter On Mac

If we want to install and run the Flutter then our development environment must meet these following minimum requirements.

  • Operating Systems: macOS (64-bit)
  • Disk Space: 700 MB (does not include disk space for IDE/tools).
  • Tools: Flutter depends on these command-line tools being available in your environment.
    • bashmkdirrmgitcurlunzipwhich

Step 1: Get the Flutter SDK

You can download the Flutter SDK from here.

Now, you need to unzip that package. You can move that unzipped folder to the project where you save all the other project folders or stay wherever it was.

Next step is to configure the System Path for flutter. To do that, you need to add the flutter path to the environment variables.

So, open the .bash_profile or .zshrc file and add the following kind of path to it.

export PATH=$PATH:/home/krunal/Desktop/code/flutter/bin

See, here the above path is mine and yours might be different. So add the correct path according to your folder structures. Save the file and exit.

Step 2: Run the Flutter Doctor

You can check out where the Flutter has the correct path or not by typing the following command.

which flutter

 

How To Install Flutter On Mac

So, here It is showing me the right path. Now run the following command.

flutter doctor

You will see something like this.

 

Install Flutter Example

Above command checks your environment and displays the report to a terminal window. The Dart SDK is bundled with a Flutter; it is not necessary to install the Dart separately. Check the output carefully for other software you may need to install or further tasks to perform the complete installation.

Step 3: Android Setup

Right now, the current version of Android Studio is 3.2. Flutter relies on the full installation of Android Studio to supply its Android platform dependencies. However, you can also write your Flutter apps in some editors like I am using Visual Studio Code. But, we need the android studio to create android virtual devices and some other dependencies.

Install Android Studio

  1. Download and install Android Studio.
  2. Start the Android Studio, and go through the ‘Android Studio Setup Wizard.’ This installs the latest Android SDK, Android SDK Platform-Tools, and Android SDK Build-Tools, which are required by the Flutter when developing a Flutter App for Android. If you have already installed then update it to the latest version as well as all the other sdks.

Set up the Android emulator

Now, to run and test your Flutter app on the Android emulator, follow these steps.

  1. Enable VM acceleration on your machine.
  2. Launch Android Studio > Tools > Android > AVD Manager and select Create Virtual Device. (The Androidsubmenu is only present when inside an Android project.)
  3. Choose a device definition and choose Next.
  4. Select one or more system images for the Android versions you want to emulate, and select Next. An x86or x86_64 image is recommended.
  5. Under Emulated Performance, select Hardware – GLES 2.0 to enable hardware acceleration.
  6. Verify the AVD configuration is correct, and select Finish. For details on the above steps, see Managing AVDs.
  7. In Android Virtual Device Manager, click Run in the toolbar. The emulator starts up and displays the default canvas for your selected OS version and device.

Step 4: IOS Setup

If we  want to develop Flutter apps for iOS, you need a Mac with Xcode 9.0 or newer. I am using XCode 10.1

Set up the iOS simulator

We can prepare to run and test your Flutter app on the iOS simulator by following these steps:

  1. On your Mac, find the Simulator via Spotlight or by using the following command:
    open -a Simulator
  2. Make sure your simulator is using a 64-bit device (iPhone 5s or later) by checking the settings in the simulator’s Hardware > Device menu.
  3. Depending on your development machine’s screen size, simulated high-screen-density iOS devices may overflow your screen. Set the device scale under the Window > Scale menu in the simulator.

Step 5: Create a new Flutter Project

As I have previously told, I am using Visual Studio Code for this project. I would like to open it and create a new project from Visual Studio Code. Now follow the steps in Visual Studio Code.

  1. Invoke View > Command Palette.
  2. Type “flutter”, and select the Flutter: New Project.
  3. Enter a project name, such as app, and press Enter.
  4. Create or select the parent directory for the new project folder.
  5. Wait for project creation to complete and the main.dart file to appear.

It will take you the file system where you can create a project folder, and that is it rest will do by the editor, and it will create a brand new project.

 

Create a new Flutter Project

Now go to the root of the project inside your terminal and type the following command.

flutter run

I have open the both Android and iOS Simulators. So it looks like this.

 

Flutter iOS and Android Projects

Finally, How To Install Flutter On Mac tutorial is over.

The post How To Install Flutter On Mac appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/10/how-to-install-flutter-on-mac/feed/ 1