Posted in Dart Flutter

Flutter – 10 Dart Syntax/Coding Tips for Quick App Development

Flutter – 10 Dart Syntax/Coding Tips for Quick App Development Posted on May 27, 2020Leave a comment
I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Flutter is very good platform for App development, it is known for its UI customizability, animations, and performance. And you can also make App for Android, web, and iOS with single codebase. The best part of Flutter I like is its UI and performance. To develop app with Flutter, you need to know Dart programming language properly.

At first, as a beginner; you might have no much knowledge of Dart language, sometimes you might code long which can be sorted out with little coding. In this article, I’m going to write some of the simple things to know about Dart. This will help you to understand App development with flutter more. Remember, this post is for very beginners.

1. Don’t list every asset, image in pubspec.yaml

When you add assets folder in pubspec.yaml file, don’t mention every file in it. You only have to add the folder, the Flutter will index all the files inside it.

flutter:
  assets:
    - assets/images/

Configure your asset folder like this, do not mention every file. With the above configuration, flutter will index every file inside assets/images/

2. Create different file to list all Constant values

Create a different file and list all the constants values like your theme color, labels, messages; which you can use it on different pages. If you need to change some colors, you have to change at only one place and changes will happen to all pages. For example:

file: lib/constants.dart

import 'package:flutter/material.dart';

const Color boxcolor = Colors.redAccent;
const String mytext = "Hello World !";

At another file, you can use this constants like below:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'constants.dart';
//import constants.dart file

class MeTry extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       body: Container( 
         color: boxcolor,
         child:Text(mytext)
       )
    );
  }
}

3. Create Different file for reusable Functions

Create different file to declare functions which are commonly used in different pages like showing error message widget function, accessing API function. Don’t declare same function in every pages. For example:

lib/functions.dart

import 'package:flutter/material.dart';

Widget errorMessage(String text){ //function that returns widget
   return Container( //return widget
      padding: EdgeInsets.all(10.00),
      margin: EdgeInsets.only(bottom: 10.00),
      color: Colors.red,
      child: Row(children: <Widget>[
         Container(
            margin: EdgeInsets.only(right:6.00),
            child: Icon(Icons.info, color: Colors.white),
          ), // icon for error message
                
          Text(text, style: TextStyle(color: Colors.white)),
          //show error message text
        ]),
    );
}

Use function form this file in different pages like below:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'functions.dart';
//importing functions file

class MeTry extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
  bool error = true;
    return Scaffold(
       body: error? //if there is any error then show error message
             errorMessage("Error message showing"):
             Text("No error message"),
    );
  }
}

4. Create Reusable AppBar and Drawer

When you make any app, it contents lots of pages and in every pages there you need to make App Bar and Drawer as well. Create reusable App bar and drawer navigation and apply it to every page. If you need to edit anything about App bar or Drawer layout, you have to edit only at one place.

See this article to create reusable AppBar and Drawer: Flutter – How to Make Reusable App Bar and Drawer Layout

5. Giving Opacity value for Color

You don’t need Opacity() widget to give opacity value to widget or color. Use the following method to give opacity to color in Flutter.

Colors.red.withOpacity(0.5) //half semi transperant color
Color.fromRGBO(30, 134, 255, 0.6) //0.6 is opacity value

6. Creating Array/List on Flutter

On Flutter, array is known as List. You can create your own array with following syntax.

List<DataType> widgetlist = [ array values here ];

For Example:

List<String> countryNames = ["Nepal", "India", "Pakistan"];
//string data type list

List<Widget> contentList = [ //widgets list 
                Container(
                  child: Text("First widget")
                ),

                SizedBox(
                  height:200,
                  child: Card()
                ),
                
                Text("Hello world"),
              ];

7. Use ternary operator to give conditional statement on child:

Ternary operator is simply a if..else conditional statement. You can apply condition on child: attribute like below.

Scaffold(
  body: error? //if there is any error then show error message
  Text("There is error"): // if there is error 
  Text("No error message"), //if there is no error
)

See this also for detail explanation: Flutter – How to use Conditional Statement (If Else) on Child Attribute

8. Use SingleChildScrollView() at outer wrapper in every page

When you publish your app, that will run in different kinds of mobiles. So use SignleChildScrollView() in every page at outermost wrapper, so that you need not to worry about overflow error in flutter.

Scaffold(
  body: SingleChildScrollView( 
     child: Container(),
  )
)

9. You can use Column or Row alternative of ListView

Column(), Row(), or Stack() widget have an attribute “children” on which you have to pass a list of Widget. Using list array you can build your own List view using these widgets. See the example below.

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

class MeTry extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

  List<String> countryList = [
         "Nepal", "India", "Pakistan", 
         "Bagaladesh", "Srilanka",
         "Bhutan", "Maldives", "Afghanistan"];

    return Scaffold(
      appBar: AppBar(title:Text("SAARC Country List")),
       body: SingleChildScrollView( 
         child: Column( 
           children:countryList.map((countryOne){
             return Card(
                  child:ListTile(
                    title: Text(countryOne),
                  )
                );
            }).toList(),
         )
       )
    );
  }
}

Output:

saarc countries flutter

10. Use Future.dealyed to make Asynchronous task on Initial State.

When you need to call any “await” command inside any function, you need to add “async” keyword with the function. But you are not allowed to add “async” keyword with initState(). Use the following method to make asynchronous tasks inside initState() function.

initState(){ //you are not allowed to apply async keyword on initState()
  Future.delayed(Duration.zero,() async {
    var response = await http.post("https://www.google.com");
    print(response);
    //if there is any await execution, you have to make function Asynchronous,
    //means the different execution will go parallelly
    //you have to add async key word to make function Asynchronous
  });
  super.initState();
}

In this way, you can make your coding more faster. I hope, you get more insight of Dart coding for flutter by this article.

I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Leave a Reply

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