Randy Rickards

Randy Rickards

1587027787

How to Create To-do app in Flutter with Parse

Parse was a popular backend service managed by Facebook until the tech giant stopped its services in 2017. However, one can still make use of their SDKs and libraries provided for range of platforms like Android, IOS to name a few, provided they setup their own server or use Back4App.

In this example, we will be using Back4App which makes use of Parse framework to provide backend services. There is one problem though that there is no official SDK for Flutter unlike other platforms but Back4app provides RESTful APIs for communicating with our backend.

Getting Started with Back4App

  1. Go ahead and create an account on Back4App.
  2. After you’ve created an account, you can then see an option to “Build a new app”. Click on that and give a name to your app (say Todo App).

This is image title

Parse console for your project.

3. You should then see a console like the one shown above.

4. On the left side you can see a section named Database Browser which lists all the classes currently present in your database. By default there are two classes present namely Role and User. Create a new class named Todo which will store the data for each Todo item.

5. You can then proceed to add a column named task to the class which will store the actual task.

Let’s code

Go ahead and create a new Flutter project.

Clear your main.dart and paste the code below so that we are on the same page.

import 'package:flutter/material.dart';
import 'package:todo_app/ui/todo_screen.dart';

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


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

Create a package named ui inside the lib folder. Inside the ui package, create a dart file named todo_screen.dart and paste the below starter code into it.

import 'package:flutter/material.dart';

class TodoScreen extends StatefulWidget {
  @override
  _TodoScreenState createState() => _TodoScreenState();
}

class _TodoScreenState extends State<TodoScreen> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Todo Screen"),
      ),
    );
  }


}

Create a constants.dart file inside lib folder where we’ll be declaring some credentials like ApplicationId and RestApiKey which we’ll be using to communicate with our backend while working with our REST APIs.

<span id="ed3e" class="jn id dt ar jj b ew jo jp r jq">_const_ **kParseApplicationId** = "Your Parse Application Id goes here";
_const_ **kParseRestApiKey** = "Your Parse Rest API key goes here";</span>

Model

Go ahead and create a package named model inside lib folder.

Inside this package create a model class named todo.dart which we’ll be using to store our “todo”. Paste the below code into it.

// To parse this JSON data, do
//
//     final todo = todoFromJson(jsonString);

import 'dart:convert';

List<Todo> todoFromJson(String str) => List<Todo>.from(json.decode(str).map((x) => Todo.fromJson(x)));

String todoToJson(List<Todo> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Todo {
  String objectId;
  String task;

  Todo({
    this.objectId,
    this.task,
  });

  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
    objectId: json["objectId"],
    task: json["task"],
  );

  Map<String, dynamic> toJson() => {
    "objectId": objectId,
    "task": task,
  };
}

Todo model class

The above class was generated using quicktype.io where you paste the json schema and it generates you a model class for your preferred language.

Network Utilties

We’ve setup our model and ui package. Now before we setup our network_utils package, we need to add a dependency named http which is used for making http requests in Flutter. I assume you know how to add dependency to your pubspec.yaml so I’ll skip this part for brevity.

Now create a package named network_utils inside your lib folder. Insisde this folder, create a class named todo_utils.dart which will handle all the network calls.

In this app, we’ll be doing four basic database operations namely CRUD (Create, Read, Update, Delete). So the basic skeleton of our todo_utils.dart keeping the operations to be performed will be like following:

import 'dart:convert';

import 'package:http/http.dart';
import 'package:todo_app/model/todo.dart';
import 'package:todo_app/constants.dart';

class TodoUtils {

  //Create
  static addTodo(Todo todo) {
  }

  //Read
  static getTodoList() {
  }
  
  //Update
  static updateTodo(Todo todo) {
  }


  //Delete
  static deleteTodo(String objectId) {

  }


}

Let’s finish up all the functions one by one before we move onto the UI part and then eventually call these functions there.

  1. Adding Todo

For adding Todo lets update our addTodo() to the following

class TodoUtils {

  static final String _baseUrl = "https://parseapi.back4app.com/classes/";


  static Future<Response> addTodo(Todo todo) async{

    String apiUrl = _baseUrl + "Todo";

    Response response = await post(apiUrl,
      headers: {
        'X-Parse-Application-Id' : kParseApplicationId,
        'X-Parse-REST-API-Key' : kParseRestApiKey,
        'Content-Type' : 'application/json'
      },
      body: json.encode(todo.toJson()),
    );

    return response;
  }
}

Let me explain this function in brief as the same format would be seen for the rest of the functions which we’ll cover

  • The variable __baseUrl_holds the url part common to all the APIs where as apiUrl is the actual API url for adding a Todo item to database.
  • As we are adding a record to the database, we are making use of post() function from the [http](https://pub.dev/packages/http#-installing-tab-) package and we are passing certain headers to this function which we had declared in our constants.dart which are used used for authentication.
  • The data passed from client to server should be json encoded so we are encoding our map returned by todo.toJson() using json.encode() from dart:convert library.

Note : The documentation for each request is also present under the API Reference section in your project console at Back4App.

Similarly, lets update the rest of the functions namely

  • getTodoList()
  • updateTodo()
  • deleteTodo()
import 'dart:convert';

import 'package:http/http.dart';
import 'package:todo_app/model/todo.dart';
import 'package:todo_app/constants.dart';

class TodoUtils {

  static final String _baseUrl = "https://parseapi.back4app.com/classes/";

  //CREATE
  static Future<Response> addTodo(Todo todo) async{

    String apiUrl = _baseUrl + "Todo";

    Response response = await post(apiUrl,
      headers: {
        'X-Parse-Application-Id' : kParseApplicationId,
        'X-Parse-REST-API-Key' : kParseRestApiKey,
        'Content-Type' : 'application/json'
      },
      body: json.encode(todo.toJson()),
    );

    return response;
  }


  //READ
  static Future getTodoList() async{

    String apiUrl = _baseUrl + "Todo";

    Response response = await get(apiUrl, headers: {
      'X-Parse-Application-Id' : kParseApplicationId,
      'X-Parse-REST-API-Key' : kParseRestApiKey,
    });

    return response;
  }
  
  
  //UPDATE
  static Future updateTodo(Todo todo) async{
    
    String apiUrl = _baseUrl + "Todo/${todo.objectId}";
    
    Response response = await put(apiUrl, headers: {
      'X-Parse-Application-Id' : kParseApplicationId,
      'X-Parse-REST-API-Key' : kParseRestApiKey,
      'Content-Type' : 'application/json',
    },
      body: json.encode(todo.toJson())
    );

    return response;
  }


  //DELETE
  static Future deleteTodo(String objectId) async{

    String apiUrl = _baseUrl + "Todo/$objectId";

    Response response = await delete(apiUrl, headers: {
      'X-Parse-Application-Id' : kParseApplicationId,
      'X-Parse-REST-API-Key' : kParseRestApiKey,
    });

    return response;
  }



}

Finishing up UI

Now we’ll proceed with the final part which is creating a UI and calling those functions which we just created.

Let’s add the code for getting the list of all the todo items from the db and displaying it on the screen. So go to your todo_screen.dart and update the code as below.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:todo_app/model/todo.dart';
import 'package:todo_app/network_utils/todo_utils.dart';

class TodoScreen extends StatefulWidget {
  @override
  _TodoScreenState createState() => _TodoScreenState();
}

class _TodoScreenState extends State<TodoScreen> {
  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text("Todo Screen"),
      ),
      body: Container(
        child: FutureBuilder(builder: (context, snapshot) {
          if (snapshot.data != null) {
            List<Todo> todoList = snapshot.data;

            return ListView.builder(itemBuilder: (_, position) {
              return ListTile(
                title: Text(todoList[position].task),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    IconButton(icon: Icon(Icons.edit), onPressed: () {
                      //Show dialog box to update item
                    }),
                    IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
                      //Show dialog box to delete item
                    })
                  ],
                ),
              );
            },
              itemCount: todoList.length,
            );

          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
          future: getTodoList(),
        ),
      ),
    );
  
  }



  Future <List<Todo>> getTodoList() async{

    List<Todo> todoList = [];

    Response response = await TodoUtils.getTodoList();
    print("Code is ${response.statusCode}");
    print("Response is ${response.body}");

    if (response.statusCode == 200) {
      var body = json.decode(response.body);
      var results = body["results"];

      for (var todo in results) {
        todoList.add(Todo.fromJson(todo));
      }

    } else {
      //Handle error
    }

    return todoList;
  }


}

So a function named getTodoList() is added which is resonsible for getting the list of todos from the server and parsing the data back from json to our model class Todo.

And a FutureBuilder is used to build the UI as the items will be returned in future after the request is completed. Till then we should show a progress bar on the screen.

Go ahead and give it a run to see our list of todo items.

This is image title

Todo Screen

Well that is because we haven’t added any yet and to add we’ll need to build functionality of add Todo first.

Add Todo Functionality

Go ahead and add a FloatingActionButton to your Scaffold on the tap of which we’ll be showing an AlertDialog to enter the Todo.


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text("Todo Screen"),
      ),
      body: Container(
        child: FutureBuilder(builder: (context, snapshot) {
          if (snapshot.data != null) {
            List<Todo> todoList = snapshot.data;

            return ListView.builder(itemBuilder: (_, position) {
              return ListTile(
                title: Text(todoList[position].task),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[ 
                    IconButton(icon: Icon(Icons.edit), onPressed: () {
                    }),
                    IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
                    })
                  ],
                ),
              );
            },
              itemCount: todoList.length,
            );

          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
          future: getTodoList(),
        ),
      ),
      floatingActionButton: FloatingActionButton(onPressed: () {
      },
        child: Icon(Icons.add),
      ),
    );
  }

Updated Scaffold

Inside the onPressed() we are going to call a function which will show user an AlertDialog to enter a new Todo item.

Before that, let’s create a global TextEditingController instance for accepting todos written by the user in AlertDialog

TextEditingController _taskController = TextEditingController();
 void showAddTodoDialog() {

    showDialog(context: context,
      builder: (_) => AlertDialog(
        content: Container(
          width: double.maxFinite,
          child: TextField(
            controller: _taskController,
            decoration: InputDecoration(
              labelText: "Enter task",
            ),
          ),
        ),
        actions: <Widget>[
          FlatButton(onPressed: () {

            Navigator.pop(context);
            addTodo();

          }, child: Text("Add")),
          FlatButton(onPressed: () {
            Navigator.pop(context);
          }, child: Text("Cancel")),
        ],
      )
    );

  }

  void addTodo() {

    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
      children: <Widget>[
        Text("Adding task"),
        CircularProgressIndicator(),
      ],
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
    ),
      duration: Duration(minutes: 1),
    ));

    Todo todo = Todo(task: _taskController.text);

    TodoUtils.addTodo(todo)
    .then((res) {

      _scaffoldKey.currentState.hideCurrentSnackBar();

      Response response = res;
      if (response.statusCode == 201) {
        //Successful
        _taskController.text = "";

        _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Todo added!"), duration: Duration(seconds: 1),));

        setState(() {
          //Update UI
        });

      }

    });

  }

So there are two new functions written inside todo_screen.dart namely showAddTodoDialog() and addTodo() for showing an AlertDialog to accept Todo and adding a Todo item to database respectively.

Call the showAddTodoDialog() inside the onPressed() of our FloatingActionButton.

floatingActionButton: FloatingActionButton(onPressed: () {
  showAddTodoDialog();
},
  child: Icon(Icons.add),
),

This is image title

Adding Todo

Update Todo Functionality

Once a Todo has been added, usershould also be able to update it. For that we’ll again show an AlertDialog with a TextField showing the existing value of the Todo. And the user can then update the Todo to whatever they want and then tap on Update button.

We’ll again be writing two functions named showUpdateDialog(Todo todo) and updateTodo() for showing AlertDialog for updating existing Todo and updating Todo in database respectively.

 void showUpdateDialog(Todo todo) {

    _taskController.text = todo.task;

    showDialog(context: context,
      builder: (_) => AlertDialog(
        content: Container(
          width: double.maxFinite,
          child: TextField(
            controller: _taskController,
            decoration: InputDecoration(
              labelText: "Enter updated task",
            ),
          ),
        ),
        actions: <Widget>[
          FlatButton(onPressed: () {
            Navigator.pop(context);
            todo.task = _taskController.text;
            updateTodo(todo);
          }, child: Text("Update")),
          FlatButton(onPressed: () {
            Navigator.pop(context);
          }, child: Text("Cancel")),
        ],
      )
    );
    
  }


  void updateTodo(Todo todo) {

    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text("Updating todo"),
        CircularProgressIndicator(),
      ],
    ),
      duration: Duration(minutes: 1),
    ),);


    TodoUtils.updateTodo(todo)
    .then((res) {

      _scaffoldKey.currentState.hideCurrentSnackBar();

      Response response = res;
      if (response.statusCode == 200) {
        //Successfully Deleted
        _taskController.text = "";
        _scaffoldKey.currentState.showSnackBar(SnackBar(content: (Text("Updated!"))));
        setState(() {

        });
      } else {
        //Handle error
      }
    });
    
  }

Call the showUpdateTodoDialog(Todo todo) inside the onPressed() of edit icon button.

return ListTile(
  title: Text(todoList[position].task),
  trailing: Row(
    mainAxisSize: MainAxisSize.min,
    children: <Widget>[ 
      IconButton(icon: Icon(Icons.edit), onPressed: () {
        showUpdateDialog(todoList[position]);
      }),
      IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
       //Call function to delete todo
      })
    ],
  ),
);

This is image title

Update Todo

We are almost done with our Todo app. We are just left with delete functionality. So let’s go do it.

Delete Todo Functionality

For deleting a todo, we’ll simply call a function to delete our Todo to keep this article short and to the point. (You can obviosly go ahead and show a confirmation dialog if you want)

void deleteTodo(String objectId) {

    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children:  <Widget>[
        Text("Deleting todo"),
        CircularProgressIndicator(),
      ],
    ),
      duration: Duration(minutes: 1),
    ),);


    TodoUtils.deleteTodo(objectId)
      .then((res) {

        _scaffoldKey.currentState.hideCurrentSnackBar();

        Response response = res;
        if (response.statusCode == 200) {
          //Successfully Deleted
          _scaffoldKey.currentState.showSnackBar(SnackBar(content: (Text("Deleted!")),duration: Duration(seconds: 1),));
          setState(() {

          });
        } else {
          //Handle error
        }
    });

  }

Call the deleteTodo(String objectId) function inside the onPressed() of the delete button.

return ListTile(
  title: Text(todoList[position].task),
  trailing: Row(
    mainAxisSize: MainAxisSize.min,
    children: <Widget>[ 
      IconButton(icon: Icon(Icons.edit), onPressed: () {
        showUpdateDialog(todoList[position]);
      }),
      IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
        deleteTodo(todoList[position].objectId);
      })
    ],
  ),
);

This is image title

Deleting Todos

So that is it. We’ve successfully built a Todo app using Parse. The source code is available on my Github

I hope you enjoyed this article, if so feel free to clap as many times you wish.

Thank you for reading!

#flutter #parse #restful apis

What is GEEK

Buddha Community

How to Create To-do app in Flutter with Parse

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Harry Patel

Harry Patel

1614145832

A Complete Process to Create an App in 2021

It’s 2021, everything is getting replaced by a technologically emerged ecosystem, and mobile apps are one of the best examples to convey this message.

Though bypassing times, the development structure of mobile app has also been changed, but if you still follow the same process to create a mobile app for your business, then you are losing a ton of opportunities by not giving top-notch mobile experience to your users, which your competitors are doing.

You are about to lose potential existing customers you have, so what’s the ideal solution to build a successful mobile app in 2021?

This article will discuss how to build a mobile app in 2021 to help out many small businesses, startups & entrepreneurs by simplifying the mobile app development process for their business.

The first thing is to EVALUATE your mobile app IDEA means how your mobile app will change your target audience’s life and why your mobile app only can be the solution to their problem.

Now you have proposed a solution to a specific audience group, now start to think about the mobile app functionalities, the features would be in it, and simple to understand user interface with impressive UI designs.

From designing to development, everything is covered at this point; now, focus on a prelaunch marketing plan to create hype for your mobile app’s targeted audience, which will help you score initial downloads.

Boom, you are about to cross a particular download to generate a specific revenue through your mobile app.

#create an app in 2021 #process to create an app in 2021 #a complete process to create an app in 2021 #complete process to create an app in 2021 #process to create an app #complete process to create an app

Hire Dedicated Flutter App Developer USA| Flutter App Developers

Hire Flutter App Developers: WebClues Infotech is a Flutter App Development company. Our Flutter mobile app development team can create cross-platform apps for different industry verticals. Our Flutter developers will help you extend your business’s scope by developing enhanced functionality and a feature-rich app. To provide a rich user experience to your users, hire dedicated Flutter app developers from WebClues Infotech today!

#hire flutter app developers #hire dedicated flutter app developer usa #hire flutter app developer usa #hire dedicated flutter app developer #hire flutter developer #flutter app development company

Best Flutter App Development Company

Are you looking for the best flutter app development company? Then AppClues Infotech is the leading flutter app development company in USA offering the best service worldwide. We focused on developing hybrid mobile apps on Android & iOS and assures our end-user about exceptional and functionally-rich mobile apps.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top flutter app development company in usa #best flutter app development service #best flutter app development company #hire flutter app developers #flutter app development company #expert flutter app development company

Best Flutter App Development Company in USA & India

AppClues Infotech is one of the best flutter app development company in USA & India. Our diverse and experienced team of developers can help you sketch the smartest and quickest solution for your mobile app development projects with the most superior technology.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top flutter app development company in usa #best flutter app development service #best flutter app development company #hire flutter app developers #flutter app development company in usa & india #custom flutter app development service