Skip to main content

Using Provider - Flutter

There are many ways to manage the state in Flutter like:

Scoped Model
BLoc
Redux
MobX

Provider is a solid state management easy to use, it is mostly syntax sugar for InheritedWidget.

Sometimes you want to have a variable living across all the application life cycle hook, if you move from one screen to another one having a way you can access those variables that you need be used during that lifetime, or maybe you want to update a variable state from other widgets different from where the action was triggered, that's something which in medium and big apps are needed, the ability to reload some widgets and not the the whole widget tree, so to that we are going to be using Provider as the state management.

let's create a new dart project with flutter create, give it the name as you want

let's create the next folder structure:

/lib/screens -> I've created 3 screens in here counter.dart, counter2.dart and reset_value.dart
/lib/blocs -> I've create 2 blocs in here counter_bloc.dart and form_bloc.dart

The first thing we need to do is to add the dependency in the pubspec.yaml file
let's go to https://pub.dev and let's find the provider package, by this time it returned me this version provider 4.0.4, let's paste under the dependencies field in the pubspec.yaml file


main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:state_management_provider/blocs/conunter_bloc.dart';

import 'blocs/form_bloc.dart';
import 'screens/counter.dart';
import 'screens/counter2.dart';
import 'screens/reset_value.dart';

void main() => runApp(
    MultiProvider(
     providers: [
       ChangeNotifierProvider<CounterBloc>.value(
         value: CounterBloc(),
       ),

       ChangeNotifierProvider<FormBloc>.value(
         value: FormBloc(),
       ),
      
     ],
     child: MyApp(),
   ),
  );

here I show you how we can added the multiprovider, and that's something we can need doing a project having several Business logic instead of just one, the second one is not doing anything at the moment, but for the purpose of the example I've just added to show you how to do it

let's keep on

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: MyHomePage(),
   );
 }
}

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {

 @override
 Widget build(BuildContext context) {
    final CounterBloc counterbloc = Provider.of<CounterBloc>(context,listen:false);
   return Scaffold(
     appBar: AppBar(
     
       title: Text("title"),
     ),
     body: Center(
     
       child: Column(
       
         mainAxisAlignment: MainAxisAlignment.center,
         children: <Widget>[

           CounterPage(),
           CounterPage2(),
           RaisedButton(
             child:Text("PUSH TO THE ANOTHER PAGE"),
             onPressed: (){

               Navigator.push(context, new MaterialPageRoute(
            
                 builder: (context)=>ResetValue())
              
               );


             },
           ),
         ],
       ),
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: (){

         counterbloc.increment();

       },
       tooltip: 'Increment',
       child: Icon(Icons.add),
     ), // This trailing comma makes auto-formatting nicer for build methods.
   );
 }
}

as you could see I have added final CounterBloc counterbloc = Provider.of<CounterBloc>(context,listen:false); and this is done to be able to avoid rendering the whole Widget tree, in order just to update something I would to do something like
Consumer<Counter>(

builder: (context,counter,child)=>Text(
"data "+counter.counter.toString()
),

)
 with a consumer.

now If I click on floatingActionButton it will call the increment button which is in the CounterBloc class, now if go to the class CounterPage in the file counter.dart


import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:state_management_provider/blocs/conunter_bloc.dart';
import 'package:state_management_provider/blocs/form_bloc.dart';

import '../blocs/conunter_bloc.dart';

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

 

 
  //FormBloc fomrbloc = Provider.of<FormBloc>(context);
 
  return Column(

    children: <Widget>[

        One(context),
        Two(context)

    ],

  );
}


Widget One(BuildContext context){

  print("from W1");
  return Text("W1");

}

Widget Two(BuildContext context){

  print("from W2");
  return Consumer<CounterBloc>(

    builder: (context,counter,child)=>Text("Data "+counter.counter.toString()),

  );

}
}

we can see here this a Widget called Two, that widget is using a Consumer and it means it just gets rendered when the notifyListener method is triggered in this case it is being triggered in the main class when I call counterbloc.increment();

in this way we can see how we can shared data accros the application using Provider

get the whole project from git hub test it and run it

https://github.com/juandavidmarin368/Fullter-Provider.git




Comments

Popular posts from this blog

How to deploy a VueJS App using Nginx on Ubuntu

There are thousands of blogs and websites out there explaining how to do a hello world and how to start with VueJS, but in this little post, I’m just going to be explaining how to do deploy a VueJs app after you have run the command through the CLI npm run build . So when you run the command npm run build a dist folder is created and that folder’s got the essential .js files to run our app, when we want to run our app on an Nginx server by default the vue-router is not going to work well so that Nginx does not come ready to work by default with a VueJs app This is basically for a Linux Ubuntu distribution if you’ve got any other Linux distribution just pay attention where is going to be set the www/html folder and the Nginx settings so that this is useful for any Linux distribution  Install and configure nginx sudo apt install nginx Double check to make sure the nginx service is running with command service nginx status, then open your browser and enter url

How to secure SpringBoot with SSL and Tomcat or Undertow

when we are going to take our applications to production mode, we must have an SSL certificate for the FrontEnd and   BackEnd too, in this case, our backend is a  SpringBoot which is using a tomcat embedded server. Terminology TLS vs SSL TLS is the successor to SSL. It is a protocol that ensures privacy between communicating applications. Unless otherwise stated, in this document consider TLS and SSL as interchangable. Certificate (cert) The public half of a public/private key pair with some additional metadata about who issued it etc. It may be freely given to anyone. Private Key A private key can verify that its corresponding certificate/public key was used to encrypt data. It is never given out publicly. Certificate Authority (CA) A company that issues digital certificates. For SSL/TLS certificates, there are a small number of providers (e.g. Symantec/Versign/Thawte, Comodo, GoDaddy, LetsEncrypt) whose certificates are included by most browsers and Operating System

How to do pagination SpringBoot with Jbctemplate, MySQL

We are going to be working on a topic which is a basic need when doing any app, and it is Pagination. let's get started creating a product table at https://mockaroo.com/ create table products ( id INT, name VARCHAR(50), code VARCHAR(50) ); insert into products (id, name, code) values (1, 'Hettinger-Goyette', '42549-680'); insert into products (id, name, code) values (2, 'Konopelski-Klein', '49527-724'); insert into products (id, name, code) values (3, 'Smitham, Kuhlman and Balistreri', '53238-003'); insert into products (id, name, code) values (4, 'Hettinger, Weissnat and Goodwin', '0143-9916'); insert into products (id, name, code) values (5, 'Rowe Inc', '42291-898'); insert into products (id, name, code) values (6, 'Ernser-Hauck', '10544-617'); insert into products (id, name, code) values (7, 'Maggio and Sons', '68788-9087'); insert into products (id, name,