Flutter - State Management using PROVIDER

Flutter - State Management using PROVIDER

In this tutorial you will see the very basics of implementing "Provider" for State management in your Flutter Applications.

In this tutorial you will see the very basics of implementing "Provider" for State management in your Flutter Applications.

So Let’s get started

Before looking into providers lets see whatsis ChangeNotifier this plugin uses ChangeNotifier to to listen and update any changes.

What is ChangeNotifier

Form docs

A class that can be extended or mixed in that provides a change notification API using [VoidCallback] for notifications.> [ChangeNotifier] is optimized for small numbers (one or two) of listeners. It is O(N) for adding and removing listeners and O(N²) for dispatching notifications (where N is the number of listeners)##

Provider

Existing providers

provider exposes a few different kinds of "provider" for different types of objects.

Let's get started with our code

first things first let add plugin to pubspec.yaml

provider: ^2.0.1
http: ^0.12.0+2

Let's Write our provider class first we name it AppState

import 'package:flutter/material.dart';

class AppState with ChangeNotifier {
  AppState();

  String _displayText = "";

  void setDisplayText(String text) {
    _displayText = text;
    notifyListeners();
  }

  String get getDisplayText => _displayText;
}

Our AppState is extended with ChangeNotifier which is used to notify its listeners when we call notifyListeners()

In the code, we declared two methods setDisplayText and getDisplayText which are used to read and write the value in our state

Now we move to our main.dart

import 'package:flutter/material.dart';
import 'package:flutter_demo_provider/app_state.dart';
import 'package:flutter_demo_provider/text_display.dart';
import 'package:flutter_demo_provider/text_edit.dart';
import 'package:provider/provider.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: ChangeNotifierProvider<AppState>(
          builder: (_) => AppState(),
          child: MyHomePage(),
        ));
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              TextDisplay(),
              TextEditWidget(),
            ],
          ),
        ),
      ),
    );
  }
}

In the code, we can notice we have used ChangeNotifierProvider which is provided from out provider plugin

It accepts two parameters one is builder and the other is child

return MaterialApp(
 title: 'Flutter Demo',
 theme: ThemeData(
 primarySwatch: Colors.blue,
 ),
 home: ChangeNotifierProvider<AppState>(
 builder: (_) => AppState(),
 child: MyHomePage(),
 ));
}

Inside the MyHomePage we have a Scaffold with Column which has two Widgets TextDisplay() and TextEditWidget()

TextDisplay(),
TextEditWidget(),

Here is out TextDisplay() in text_display.dart

import 'package:flutter/material.dart';
import 'package:flutter_demo_provider/app_state.dart';
import 'package:provider/provider.dart';

class TextDisplay extends StatefulWidget {
  @override
  _TextDisplayState createState() => _TextDisplayState();
}

class _TextDisplayState extends State<TextDisplay> {
  @override
  Widget build(BuildContext context) {
    final appState = Provider.of<AppState>(context);

    return Container(
      padding: const EdgeInsets.all(16.0),
      child: Text(
        appState.getDisplayText,
        style: TextStyle(
          fontSize: 24.0,
        ),
      ),
    );
  }
}

In the above code we see

Widget build(BuildContext context) {
 final appState = Provider.of<AppState>(context);

 return Container(
 padding: const EdgeInsets.all(16.0),
 child: Text(
 appState.getDisplayText,
 style: TextStyle(
 fontSize: 24.0,
 ),
 ),
 );
}
final appState = Provider.of<AppState>(context);

This above line of code will get the provider for listening for any changes optionally we can also opt-out for listening by proving listen: false

final appState = Provider.of<AppState>(context, listen: false);

Now in order to access text, we have a function in our provider called getDisplayText

appState.getDisplayText()

Here is out TextEditWidget() in text_edit.dart

  
import 'package:flutter/material.dart';
import 'package:flutter_demo_provider/app_state.dart';
import 'package:provider/provider.dart';

class TextEditWidget extends StatefulWidget {
  @override
  _TextEditWidgetState createState() => _TextEditWidgetState();
}

class _TextEditWidgetState extends State<TextEditWidget> {
  TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final appState = Provider.of<AppState>(context);

    return Container(
      child: TextField(
        controller: _textEditingController,
        decoration: InputDecoration(
          labelText: "Some Text",
          border: OutlineInputBorder(),
        ),
        onChanged: (changed) => appState.setDisplayText(changed),
        onSubmitted: (submitted) => appState.setDisplayText(submitted),
      ),
    );
  }
}

In the above code, we get our appState inside the build function

final appState = Provider.of<AppState>(context);

In order to manipulate the text in the state we call setDisplayText(text) function

TextField(
 controller: _textEditingController,
 decoration: InputDecoration(
 labelText: "Some Text",
 border: OutlineInputBorder(),
 ),
 onChanged: (changed) => appState.setDisplayText(changed),
 onSubmitted: (submitted) => appState.setDisplayText(submitted),
)

we are updating the state whenever out text is changes

onChanged: (changed) => appState.setDisplayText(changed)

Now we perform network operation

Now inside our app state, we have some additional functions and variables

String _dataUrl = "https://reqres.in/api/users?per_page=20";
String _jsonResonse = "";
bool _isFetching = false;

bool get isFetching => _isFetching;

Future<void> fetchData() async {
 _isFetching = true;
 notifyListeners();

 var response = await http.get(_dataUrl);
 if (response.statusCode == 200) {
 _jsonResonse = response.body;
 }

 _isFetching = false;
 notifyListeners();
}

String get getResponseText => _jsonResonse;

List<dynamic> getResponseJson() {
 if (_jsonResonse.isNotEmpty) {
 Map<String, dynamic> json = jsonDecode(_jsonResonse);
 return json['data'];
 }
 return null;
}

Here we have a few more functions fetchData, getResponseText and getResponseJson

fetchData will perform the network operation and update the variable with the response data (you can parse your JSON to custom model here and save it in a List)

getResponseText will return the plain text response

getResponseJson will convert the response text to a Map and returndata field inside it which is a list of Map

To see the final app_state.dart visit below link

Now inside out MyHomePage widget we add two more widgets to our column

RaisedButton(
 onPressed: () => appState.fetchData(),
 child: Text("Fetch Data from Network"),
),
ResponseDisplay(),

So I am calling appState.fetchData() whenever I press the button now fetchData will take care of all the updating of the state on Github

Here is our ResponseDisplay Widget named response_display.dart

  
import 'package:flutter/material.dart';
import 'package:flutter_demo_provider/app_state.dart';
import 'package:provider/provider.dart';

class ResponseDisplay extends StatefulWidget {
  @override
  _ResponseDisplayState createState() => _ResponseDisplayState();
}

class _ResponseDisplayState extends State<ResponseDisplay> {
  @override
  Widget build(BuildContext context) {
    final appState = Provider.of<AppState>(context);

    return Container(
      padding: const EdgeInsets.all(16.0),
      child: appState.isFetching
          ? CircularProgressIndicator()
          : appState.getResponseJson() != null
              ? ListView.builder(
                  primary: false,
                  shrinkWrap: true,
                  itemCount: appState.getResponseJson().length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      leading: CircleAvatar(
                        backgroundImage: NetworkImage(
                            appState.getResponseJson()[index]['avatar']),
                      ),
                      title: Text(
                        appState.getResponseJson()[index]["first_name"],
                      ),
                    );
                  },
                )
              : Text("Press Button above to fetch data"),
    );
  }
}

Here in the above code we parse the JSON and build a list of data

To get the code it's here on GitHub

Flutter Grocery Shopping Mobile App

Flutter Grocery Shopping Mobile App

This Flutter grocery app is a pro version that has all features of online grocery purchase for your customers.

FLUTTER GROCERY APP
Are you looking to launch your online grocery shop or any E-Commerce mobile app then this flutter grocery app will help you to build the app in just days? We offer an online grocery software system. The mobile application offers amazing features to build a powerful online ordering system or app for your grocery shop. It enhances online home grocery stuffs ordering experience for your customers with your mobile grocery app. This Flutter grocery app is a fully functional mobile app that has all features of online grocery purchase for your customers. So what are you waiting for? Start your online business with your Mobile app today!

YOu check live demo and feature video at:
https://www.youtube.com/watch?v=Y0bn_3Uu2u0

Flutter App Development Company | Hire Flutter App Developers

When it comes to Hybrid Mobile App Development Framework, Flutter is gaining the momentum. And, we as top development company don't hesitate to say that it is going to be future cross-platform mobile app development. Though there are few other frameworks available for cross-platform and hybrid mobile app development, Flutter is an increasing trend. In fact, intellectuals are comparing Flutter vs. React Native vs. Ionic and finding the best solutions out of them. Some of the top companies have already adapted Flutter, and they are very positive about it.

When it comes to Hybrid Mobile App Development Framework, Flutter is gaining the momentum. And, we as top development company don't hesitate to say that it is going to be future cross-platform mobile app development. Though there are few other frameworks available for cross-platform and hybrid mobile app development, Flutter is an increasing trend. In fact, intellectuals are comparing Flutter vs. React Native vs. Ionic and finding the best solutions out of them. Some of the top companies have already adapted Flutter, and they are very positive about it.


Flutter is the future of mobile app development 👏👏👏

Flutter is the future of mobile app development 👏👏👏

Flutter is a new mobile app SDK to help developers and designers build modern mobile apps for iOS and Android.” The modern, reactive ...🎁🎁🎁🎁

Flutter is a new mobile app SDK to help developers and designers build modern mobile apps for iOS and Android.” The modern, reactive ...

I dabbled a bit in Android and iOS development quite a few years back using Java and Objective-C. After spending about a month working with both of them, I decided to move on. I just couldn’t get into it.

But recently, I learned about Flutter and decided to give mobile app development another shot. I instantly fell in love with it as it made developing multi-platform apps a ton of fun. Since learning about it, I’ve created an app and a library using it. Flutter seems to be a very promising step forward and I’d like to explain a few different reasons why I believe this.

Powered by Dart

Flutter uses the Google-developed Dart language. If you’ve used Java before, you’ll be fairly familiar with the syntax of Dart as they are quite similar. Besides the syntax, Dart is a fairly different language.

I’m not going to be talking about Dart in depth as it’s a bit out of scope, but I’d like to discuss one of the most helpful features in my opinion. This feature being support for asynchronous operations. Not only does Dart support it, but it makes it exceptionally easy.

This is something you’ll most likely be using throughout all of your Flutter applications if you’re doing IO or other time-consuming operations such as querying a database. Without asynchronous operations, any time-consuming operations will cause the program to freeze up until they complete. To prevent this, Dart provides us with the async and await keywords which allow our program to continue execution while waiting for these longer operations to complete.

Let's take a look at a couple of examples: one without asynchronous operations and one with.

// Without asynchronous operations
	import 'dart:async';
	

	main() {
	    longOperation();
	    printSomething();
	}
	

	longOperation() {
	    Duration delay = Duration(seconds: 3);
	    Future.delayed(delay);
	    print('Waited 3 seconds to print this and blocked execution.');
	}
	

	printSomething() {
	    print('That sure took a while!');
	}

And the output:

3 seconds to print this and blocked execution.
That sure took a while!

This isn’t ideal. No one wants to use an app that freezes up when it executes long operations. So let’s modify this a bit and make use of the async and await keywords.

// With asynchronous operations
	import 'dart:async';
	

	main() {
	    longOperation();
	    printSomething();
	}
	

	Future<void> longOperation() async {
	    var retVal = await runLongOperation();
	

	    print(retVal);
	}
	

	const retString = 'Waited 3 seconds to return this without blocking execution.';
	Duration delay = Duration(seconds: 3);
	

	Future<String> runLongOperation() => Future.delayed(delay, () => retString);
	

	printSomething() {
	    print('I printed right away!');
	}

And the output once again:

I printed right away!
Waited 3 seconds to return this without blocking execution.

Thanks to asynchronous operations, we’re able to execute code that takes a while to complete without blocking the execution of the rest of our code.

Write Once, Run on Android and iOS

Developing mobile apps can take a lot of time considering you need to use a different codebase for Android and iOS. That is unless you use an SDK like Flutter, where you have a single codebase that allows you to build your app for both operating systems. Not only that, but you can run them completely natively. This means things such as scrolling and navigation, to name a few, act just like they should for the OS being used.

To keep with the theme of simplicity, as long as you have a device or simulator running, Flutter makes building and running your app for testing as simple as clicking a button.

UI Development

UI development is one of those things that I almost never look forward to. I’m more of a backend developer, so when it comes to working on something that is heavily dependent on it, I want something simple. This is where Flutter shines in my eyes.

UI is created by combining different widgets together and modifying them to fit the look of your app. You have near full control over how these widgets display, so you’ll always end up with exactly what you’re looking for. For laying out the UI, you have widgets such as Row, Column, and Container. For content, you have widgets like Text and RaisedButton. This is only a few of the widgets Flutter offers, there are a lot more. Using these widgets, we can build a very simple UI:

@override
	Widget build(BuildContext context) {
	    return Scaffold(
	        appBar: AppBar(
	            title: Text('Flutter App'),
	            centerTitle: true,
	            elevation: 0,
	        ),
	        body: Row(
	            mainAxisAlignment: MainAxisAlignment.center,
	            children: [
	                Column(
	                    mainAxisAlignment: MainAxisAlignment.center,
	                    children: [
	                        Container(
	                            child: Text('Some text'),
	                        ),
	                        Container(
	                            child: RaisedButton(
	                                onPressed: () {
	                                    // Do something on press
	                                },
	                                child: Text('PRESS ME'),
	                            ),
	                        ),
	                    ],
	                ),
	            ],
	        ),
	    );
	}

Flutter has more tricks up its sleeve that makes theming your app a breeze. You could go through and manually change the fonts, colors, and looks for everything one by one, but that takes way too long. Instead, Flutter provides us with something called ThemeData that allows us to set values for colors, fonts, input fields, and much more. This feature is great for keeping the look of your app consistent.

theme: ThemeData(
	    brightness: Brightness.dark,
	    canvasColor: Colors.grey[900],
	    primarySwatch: Colors.teal,
	    primaryColor: Colors.teal[500],
	    fontFamily: 'Helvetica',
	    primaryTextTheme: Typography.whiteCupertino.copyWith(
	        display4: TextStyle(
	            color: Colors.white,
	            fontSize: 36,
	        ),
	    ),
	),

With this ThemeData, we set the apps colors, font family, and some text styles. Everything besides the text styles will automatically be applied app-wide. Text styles have to be set manually for each text widget, but it's still simple:

child: Text(
	   'Some text',
	   style: Theme.of(context).primaryTextTheme.display4,
),

To make things even more efficient, Flutter can hot reload apps so you don’t need to restart it every time you make a change to the UI. You can now make a change, save it, then see the change within a second or so.

Libraries

Flutter provides a lot of great features out of the box, but there are times when you need a bit more than it offers. This is no problem at all considering the extensive number of libraries available for Dart and Flutter. Interested in putting ads in your app? There’s a library for that. Want new widgets? There are libraries for that.

If you’re more of a do-it-yourselfer, make your own library and share it with the rest of the community in no time at all. Adding libraries to your project is simple and can be done by adding a single line to your pubspec.yaml file. For example, if you wanted to add the sqflite library:

dependencies:
 flutter:
  sdk: flutter
 sqflite: ^1.0.0

After adding it to the file, run flutter packages get and you're good to go. Libraries make developing Flutter apps a breeze and save a lot of time during development.

Backend Development

Most apps nowadays depend on some sort of data, and that data needs to be stored somewhere so it can be displayed and worked with later on. So keeping this in mind when looking to create apps with a new SDK, such as Flutter, is important.

Once again, Flutter apps are made using Dart, and Dart is great when it comes to backend development. I’ve talked a lot about simplicity in this article, and backend development with Dart and Flutter is no exception to this. It’s incredibly simple to create data-driven apps, for beginners and experts alike, but this simplicity by no means equates to a lack of quality.

To tie this in with the previous section, libraries are available so you can work with the database of your choosing. Using the sqflite library, we can be up and running with an SQLite database fairly quickly. And thanks to singletons, we can access the database and query it from practically anywhere without needing to recreate an object every single time.

class DBProvider {
	    // Singleton
	    DBProvider._();
	

	    // Static object to provide us access from practically anywhere
	    static final DBProvider db = DBProvider._();
	    Database _database;
	

	    Future<Database> get database async {
	        if (_database != null) {
	            return _database;
	        }
	

	        _database = await initDB();
	        return _database;
	    }
	

	    initDB() async {
	        // Retrieve your app's directory, then create a path to a database for your app.
	        Directory documentsDir = await getApplicationDocumentsDirectory();
	        String path = join(documentsDir.path, 'money_clip.db');
	

	        return await openDatabase(path, version: 1, onOpen: (db) async {
	            // Do something when the database is opened
	        }, onCreate: (Database db, int version) async {
	            // Do something, such as creating tables, when the database is first created.
	            // If the database already exists, this will not be called.
	        }
	    }
	}

After retrieving data from a database, you can convert that to an object using a model. Or if you want to store an object in the database, you can convert it to JSON using the same model.

class User {
	    int id;
	    String name;
	

	    User({
	        this.id,
	        this.name,
	    });
	

	    factory User.fromJson(Map<String, dynamic> json) => new User(
	        id: json['id'],
	        name: json['name'],
	    );
	

	    Map<String, dynamic> toJson() => {
	        'id': id,
	        'name': name,
	    };
}

This data isn’t all that useful without a way to display it to the user. This is where Flutter comes in with widgets such as the FutureBuilder or StreamBuilder. If you're interested in a more in-depth look at creating data-driven apps using Flutter, SQLite, and other technologies, I encourage you to check out the article I wrote on that:

https://medium.com/@erigitic/using-streams-blocs-and-sqlite-in-flutter-2e59e1f7cdce

Final Thoughts

With Flutter, the possibilities are practically endless, so even super extensive apps can be created with ease. If you develop mobile apps and have yet to give Flutter a try, I highly recommend you do as I’m sure you’ll fall in love with it as well. After using Flutter for quite a few months, I think it’s safe to say that it’s the future of mobile development. If not, it’s definitely a step in the right direction.