Category Archives: Flutter

Create listview widget in flitter


We have seen how to create a custom widgets, how about a Listview ?

This post uses the sample code from my project ‘Dashboard app

It will construct with combination of two part first part draw item layout for Listview, this can be done with Card and bunch of other widget.

I created a function for this in my Stateless widget so that Listview builder can use this Card Widget and the second part with Listview.Builder

class DistrictList extends StatelessWidget {
  final List<DistInfo> dist;

  const DistrictList({Key key, this.dist}) : super(key: key);

  Widget _buildDistirictInfo(BuildContext context, int index) {
    return Card(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          ListTile(
            onTap: () {
              Navigator.push(
                  context,
                  new MaterialPageRoute(
                      builder: (context) => DistrictDetailPage(
                            distInfo: dist[index],
                          )));
            },
            hoverColor: Colors.grey,
            focusColor: Colors.deepOrange,
            leading: CircleAvatar(
              child: Text(dist[index].dname.substring(0, 2).toUpperCase()),
              backgroundColor: Colors.greenAccent,
            ),
            title: Text(
              dist[index].dname,
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            trailing: Icon(Icons.apps),
            shape: StadiumBorder(),
            subtitle: Text(
              "Recovered  " +
                  dist[index].status.recovered.toString() +
                  " | " +
                  "Confirmed  " +
                  dist[index].status.confirmed.toString(),
              style: TextStyle(
                  color: Colors.brown,
                  fontSize: 15,
                  fontWeight: FontWeight.bold),
            ),
          )
        ],
      ),
    );
  }

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

The widget get data from the list which is passed to it in the parent widget as follows.

To make a complete comprehension I recommend you to take a look at Github Repository.

class StateDetailPage extends StatelessWidget {
  @override
  final StateInfo info;

  const StateDetailPage({Key key, this.info}) : super(key: key);

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            info.sname,
          ),
        ),
        bottomNavigationBar: BottomAppBar(
          color: Colors.brown,
          child: Container(
            alignment: Alignment.center,
            color: Colors.white,
            child: Wrap(
              children: [
                GestureDetector(
                  child: Tooltip(
                    message: 'Refressh',
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Icon(
                        Icons.home,
                        size: 40,
                      ),
                    ),
                  ),
                  onTap: () {
                    Navigator.push(context,
                        new MaterialPageRoute(builder: (context) => MyApp()));
                  },
                ),
                SizedBox(
                  width: 35,
                ),
                Tooltip(
                  message: 'District Data',
                  child: GestureDetector(
                    onTap: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) =>
                                  DistrictReport(distList: info.distInfo)));
                    },
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Icon(
                        Icons.recent_actors,
                        color: Colors.brown,
                        size: 40,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            height: 50,
          ),
        ),
        body: Container(
            child: Column(
          children: <Widget>[
            TestStatus(
              result: info.tests,
            ),
            Expanded(
                child: DistrictList(
              dist: info.distInfo,
            ))
          ],
        )));
  }
}

Flutter Android Covid Dashboard Project


I am happy to introduce this open source project which is another extension of my Python-Flask Dashboard project.

This app will serve as utility as well as tutorial source which let you know how to use Json data in conjunction with Flutter Future.

The app bring me daily Covid Pandemic status for Indian state which get me Tests status of districts and state level.

The source code of the project is available on the Github repo, so anybody can use it. For more info on my portfolio

Add permission in Flutter Android app


Flutter simplify the app development with ease and peace, I enjoy a lot of Fluttering. In this post we learn how to add Android Permissions in Flutter.

Flutter has its own packages to check for permission. Before using the permissions ,other than the Emulator you have to add the flowing line in android\app\src\main\AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.flutter_c19dashboard">
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="C19 Dashboard"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

Book Keeper Free


Download Book Keeper Personal Edition – A accounting package for Windows users

Search Dart dynamic json collection in Flutter


I am familiar with Lynq operation in C# , which I think one of the flexible tools the language provide us. Dart and Flutter has same feature , may be all modern language have them.

I this example I will show you how dynamic or any collection can filtered in Dart. We have a Json extracted collection which is a Linked list, the collection is extracted in the following way. (so you can understand how I get those)

var test_data =
          await http.get('https://api.covid19india.org/state_test_data.json');
      var tdata = json.decode(test_data.body);

Filtering the List

The about code is a part of a Covid Dashboard Example , which is a Flutter native app project. The source can be found on my GitHub Repo, in case you need them.

The list includes dictionary key,value pair , so I can search for them using the where. To do this I first covert the data into a List.

 var t_data = tdata['states_tested_data'] as List;

Then we can use where to filter the list using keys and get the list. Remember in place filter didn’t change any thing as follows.

t_data.where((element) =>element['state'] == 'Kerala')

we can get another list from the above as follows which what exactly we needed.

var l = t_data.where((element) =>
                 element['state'] == 'Delhi').toList();

Explore other Dart article to learn more about Dart and Flutter

Create a custom RawMaterial button in Flutter


Custom buttons help us create new UI with additional feature, Flutter allows you to create awesome controls/widgets combining existing ones. Our material button have following features

  • Icon
  • Icon Color
  • Splash color
  • Back ground color
  • Shape
  • title

To make this possible we used 7 widgets , lets checkout the code

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
//This Widget written by [manojap.github.io]
class MButon extends StatelessWidget {
  MButon({@required this.onPressed,@required this.title, this.style, this.splash, this.background_color, this.newshape, this.newicon, this.iconColor});
  final String title;
  final GestureTapCallback onPressed;
  final TextStyle style;
  final Color splash;
  final Color background_color;
  final ShapeBorder newshape;
  final IconData newicon;
  final Color iconColor;

  @override
  Widget build(BuildContext context) {
    return RawMaterialButton(
      fillColor: background_color,
      splashColor: splash,
      shape:newshape!=null ? newshape:  const StadiumBorder(),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 20),
        child: Row(mainAxisSize: MainAxisSize.min,
          children:  [
            Icon(
              newicon!=null ? newicon : Icons.help,
              color: iconColor!=null ? iconColor: Colors.amber,
            ),
            SizedBox(
              width: 8,
            ),
             Text(
              title,
              style: style,
            ),
          ],
        ),
      ),
      onPressed: onPressed,
    );
  }
}

We have used Padding to accommodate space between borders and Text, so that the Text widget look neat and nice. A SizeBox widget is placed between Icon and the Text Widgets which add blank space.

You also noticed that we have checked for nulls make sure the Shape property not null ( It will fire an error , if it leave blank), if so it used an stadium border. You can also use the other borders like

RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10))),

Example

Here is Quick and Simple Floating button. Include the .dart[the above code] file to lib directory and import in main.drt.

MButon(
        title: 'About',
        style: TextStyle(color: Colors.black),
        background_color: Colors.deepOrange,
        splash: Colors.orange,
        newshape: RoundedRectangleBorder(
           borderRadius: BorderRadius.all(Radius.circular(10))),
        onPressed: () { 
})

The complete code and other Widgets projects can be located @ Flutter-Widgets GitHub Repository

Checking null inside a widget in Flutter


This is Flutter series, if you not familiar with Flutter development here is the post for you.

Encounter and treat null is a should have in development cycle. We know how to deal with null around class, objects and functions too. So how about widget and properties.

I have customized a Material button (I will pull that stuff in the next post) which accepting different type of borders, StadiumBorder() like stuff. By default I want to set StadiumBorder, if user not passing any values. Possibly fire an error on default value for shape.

So how do we check null ?

Here is the solution

shape:newshape!=null ? newshape:  const StadiumBorder(),

I check for the new value for shape , if it fails I use a default one. Quiet simple , isn’t it.

Flutter Widget of the day : Wrap


Welcome to another Flutter Widget of the Day post. Today we have Wrap widget. Look at the following screen shot

Flutter Row with unfitted elements

Behind the scene

 body: Center(

        child: Row(


          children: <Widget>[
           FlatButton(child: Text('Butto1'),),
           FlatButton(child: Text('Butto2'),),
           FlatButton(child: Text('Butto3'),),
           FlatButton(child: Text('Butto4'),),
           FlatButton(child: Text('Butto5'),),
           FlatButton(child: Text('Butto6'),),


          ],
        ),
      ),

As we know for arranging controls in horizontal manner we use Row widget and for vertical use Column widget.

The screen bump with a Yellow bar, which is caused by controls that is not fitted on the screen. Flutter has beautiful way of showing Errors, lol.

To solve the issue like this, Flutter has a special Widget called Wrap which wrap the contents to next line as we saw on the following screenshot

Replace Row with Wrap

and the code will be as follows

body: Center(

        child: Wrap(spacing: 3,


          children: <Widget>[
           FlatButton(child: Text('Butto1'),),
           FlatButton(child: Text('Butto2'),),
           FlatButton(child: Text('Butto3'),),
           FlatButton(child: Text('Butto4'),),
           FlatButton(child: Text('Butto5'),),
           FlatButton(child: Text('Butto6'),),


          ],
        ),
      ),

Wrap has property children as Rows has ,so we can lay the controls as in Rows. It has many other property such as spacing which is handy . And the following quick video will help you further.

Flutter Widget of the day : AboutDialog


Welcome to another Flutter Widget of the Day post. Today we have AboutDialog widget, which can be must have for every app, since every developer tech like to have some license info for the users.

How to use the AboutDialog

It is a good idea to create function to show the dialog which return a AboutDialog in a Flutter Manner as follows.

 void showAboutDialog({
    @required BuildContext context,
    String applicationName,
    String applicationVersion,
    Widget applicationIcon,
    String applicationLegalese,
    List<Widget> children,
    bool useRootNavigator = true,
    RouteSettings routeSettings,
  }) {
    assert(context != null);
    assert(useRootNavigator != null);
    showDialog<void>(
      context: context,
      useRootNavigator: useRootNavigator,
      builder: (BuildContext context) {
        return AboutDialog(
          applicationName: applicationName,
          applicationVersion: applicationVersion,
          applicationIcon: applicationIcon,
          applicationLegalese: applicationLegalese,
          children: children,
        );
      },
      routeSettings: routeSettings,
    );
  }

Now we are ready for calling the function inside the floating Actions button. You can now add all relevant information about your app, name, icon, version, etc as follows

 floatingActionButton: FloatingActionButton(
        child: Icon(Icons.help),
        onPressed: () {
          showAboutDialog(
              context: context,
              applicationName: "My APP",
              applicationVersion: "Beta",
              children: [
                Text('Developer: Manoj A.P'),
                Text('can be reached @ manojap@outlook.com'),
                Text('Web:' + 'http://manojap.github.io')
              ],
              applicationIcon: Icon(Icons.games));
        },
      ),

Besides there is children : [ ] which is used to add additional information in case you need them as a list of Widgets of your choice.

You may already noticed that flutter automatically included package license info for you, it can also be done manually

Create a custom Flutter Text Widget


A Custom Widget can be composed of many widgets , in our Neat Textbox widget we used Decorated Box, BoxDecoration and Padding.

To make new widget first have to extend a class from StatelessWidget and then provide final variables , constructor and build method

The build method is the heart of any widget

Our NeattextBox accepting Text Styles ,so we have a final variable styl, it help us to use different font, color and other style properties

Padding used to adjust distance the boarder using EdgeInsets , also se the alignment of the Text. You can also utilize other BoxDecoration property as you wish

NeattexBox Widget

class NeattextBox extends StatelessWidget {
  final String title;
  final TextStyle styl;

  const NeattextBox({Key key, @required this.title, this.styl})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
        decoration: BoxDecoration(color: Colors.white),
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            title,
            textAlign: TextAlign.left,
            style: styl,
          ),
        ));
  }
}

How to use the New Box

Here is the sample code implement the widget with styl

NeattextBox(
                styl: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                    color: Colors.deepOrangeAccent),
                title: "Dead :" + dist.status.deceased.toString(),
              )

Flutter Widget of the day : SafeArea


SafeArea is must have widget for any app developing with Flutter and Dart. So what is SafeArea for ?

As the name indicates it secure the mostly you want to cover, it helps to prevent overlapping of UI to Notification area, bottom navigation and edges of the screen. So you can keep the app away from different type of notches, curved edges , and other hardware features.

All you have to do is to wrap your widgets with SafeArea() widget as follows

 SafeArea(
        child: Scaffold(