Flutter Dev

Flutter Dev

1632298931

Using Provider with Redux

provider_for_redux

With Provider you can inject your state, but it's your job to figure out how to update that state, structure the solution etc. In other words, Provider is a great alternative to InheritedWidget, and lets you do dependency injection, but you still need to do your own state management.

What people mean by “Provider as state management” is usually using Provider to do scoped model. But as a matter of fact, this is not the only possible architecture using Provider. You can use it with Bloc, Mobx, Redux and other.

This package lets you use it with AsyncRedux, the non-boilerplate version of Redux.

How to use it

Please, read the async_redux documentation first, if you haven't already.

You should have learned that to use AsyncRedux the traditional way, you provide the Redux store to your app by wrapping it with a StoreProvider, and then using the so called "connector" widgets, like the MyHomePageConnector below:

@override
Widget build(BuildContext context) =>
    StoreProvider<AppState>(
        store: store,
        child: MaterialApp(
          home: MyHomePageConnector(),
        ));

Now, if you want to use AsyncRedux with Provider, simply remove the StoreProvider and use AsyncReduxProvider instead. Also, you won't need the connector widgets anymore, since you will use Provider instead.

For example:

@override
Widget build(BuildContext context) =>
    AsyncReduxProvider<AppState>.value( // Instead of StoreProvider.
        value: store,
        child: MaterialApp(
          home: MyHomePage(), // Instead of MyHomePageConnector. 
        ));

The AsyncReduxProvider widget above will expose the store, the state, and the dispatch method to its descendants:

  • The Redux store, of type Store. Get it like this: Provider.of<Store<AppState>>(context).
  • The store's state, of type AppState. Get it like this: Provider.of<AppState>(context).
  • The dispatch method, of type Dispatch. Get it like this: Provider.of<Dispatch>(context).

This is a complete example:

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

  int counter(context) =>
      Provider
          .of<AppState>(context)
          .counter;

  String description(context) =>
      Provider
          .of<AppState>(context)
          .description;

  VoidCallback onIncrement(context) =>
          () => Provider.of<Dispatch>(context, listen: false)(IncrementAndGetDescriptionAction());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Increment Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("You've pushed the button:"),
            Text('${counter(context)}', style: TextStyle(fontSize: 30)),
            Text('${description(context)}', style: TextStyle(fontSize: 15)),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: onIncrement(context),
        child: Icon(Icons.add),
      ),
    );
  }
}

Try running the Provider.of example.

Consumer

You can use Provider's Consumer class to read from the store. For example:

return Consumer<Store<AppState>>(
builder: (context, store, child) =>
...
Text('${store.state.counter}'),
...
onPressed: () => store.dispatch(
IncrementAction
(
)
)
,
)
,

But it's easier if you use ReduxConsumer, which already gives you the store, the state, and the dispatch method:

return ReduxConsumer<AppState>(
builder: (context, store,
state
,
dispatch
,
child
)
=>
...

This is a complete example:

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

  @override
  Widget build(BuildContext context) {
    return ReduxConsumer<AppState>(
      builder: (context, store, state, dispatch, child) => Scaffold(
        appBar: AppBar(title: Text('Increment Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("You've pushed the button:"),
              Text('${state.counter}', style: TextStyle(fontSize: 30)),
              Text('${state.description}', style: TextStyle(fontSize: 15)),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => dispatch(IncrementAndGetDescriptionAction()),
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

Try running the ReduxConsumer example.

Selector

You can use Provider's Selector class to read from the store, while preventing unnecessary widget rebuilds. For example:

return Selector<Store<AppState>, Tuple2<int, Dispatch>>(

   selector: (context, store) => 
      Tuple2(store.state.counter, store.dispatch),

   builder: (context, model, child) => 
      ...     
      Text('${model.item1}'),
      ...
      onPressed: () => model.item3(IncrementAction()),      
      ),

Your selector parameter must return a "model" which you can use to build your widget in the builder parameter. In the above example the model is a Tuple2 instance, but you can return any immutable object that correctly implements equals and hashcode. The widget will rebuild whenever the model changes.

But it's easier if you use ReduxSelector, which already gives you the store, the state, and the dispatch method:

return ReduxSelector<AppState, Tuple2<int, String>>(
selector: (context, state) => Tuple2(state.counter, store.dispatch),

builder: (ctx, store, state, dispatch, model, child) =>
...
Text('${state.counter}'),
...
onPressed: () => store.dispatch(IncrementAction()
)
,
)
,

Try running the ReduxSelector with model example.

However, ReduxSelector also lets you return a List as the model. In case you do that, it will rebuild the widget whenever any of the items in the list changes:

return ReduxSelector<AppState, dynamic>(
selector: (context, state) => [...],
builder: (context, store, state, dispatch, model,
child
)
=>
...    

Using ReduxSelector with a list is the easiest way of all, since you just need to list all of the state parts that should trigger a rebuild.

Note: The builder gives you both the state and the model, and you can choose one of them to build your widget from. While using state is probably easier for you, it's also easier to accidentally use something you forget to add to the model, and then wonder why the Widget doesn't rebuild. So you have two options:

  1. Use only the model and have the compiler make sure there's no state you're using from outside of the model.
  2. Use state directly, and have yourself the responsibility to make you've listed everything you' re using in the model.

This is a complete example:


Widget build(BuildContext context) {       
  return ReduxSelector<AppState, dynamic>(
     
      selector: (context, state) => [
                                    state.counter, 
                                    state.description
                                    ],

      builder: (context, store, state, dispatch, model, child) => 
         Scaffold(
             appBar: AppBar(title: Text('Increment Example')),
             body: Center(
               child: Column(
                 mainAxisAlignment: MainAxisAlignment.center,
                 children: [
                   Text("You've pushed the button:"),
                   Text('${state.counter}', style: TextStyle(fontSize: 30)),
                   Text('${state.description}', style: TextStyle(fontSize: 15)),
                 ],
               ),
             ),
             floatingActionButton: FloatingActionButton(
               onPressed: () => dispatch(IncrementAndGetDescriptionAction()),
               child: Icon(Icons.add),
             )));
}

Try running the ReduxSelector with list example.

Migrating

When you use AsyncReduxProvider you will notice that both Provider and AsyncRedux's StoreConnector will work simultaneously. You can mix and match both of them, as desired, or slowly migrate between them.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add provider_for_redux

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  provider_for_redux: ^4.0.0

Alternatively, your editor might support or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:provider_for_redux/provider_for_redux.dart';

example/lib/main.dart

import 'package:async_redux/async_redux.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_for_redux/provider_for_redux.dart';

import 'actions.dart';
import 'app_state.dart';

// Developed by Marcelo Glasberg (Aug 2019).
// For more info, see: https://pub.dartlang.org/packages/provider_for_redux

late Store<AppState> store;

/// This example shows how to use `Provider.of` to access the Redux store.
///
/// Note: This example uses http. It was configured to work in Android, debug mode only.
/// If you use iOS, please see:
/// https://flutter.dev/docs/release/breaking-changes/network-policy-ios-android
///
void main() {
  var state = AppState.initialState();
  store = Store<AppState>(initialState: state);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => AsyncReduxProvider<AppState>.value(
        value: store,
        child: const MaterialApp(home: MyHomePage()),
      );
}

///////////////////////////////////////////////////////////////////////////////

/// The screen has a counter, a text description, and a button.
/// When the button is tapped, the counter will increment synchronously,
/// while an async process downloads some text description.
class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  int? counter(BuildContext ctx) => Provider.of<AppState>(ctx).counter;

  String description(BuildContext ctx) => Provider.of<AppState>(ctx).description;

  VoidCallback onIncrement(BuildContext ctx) =>
      () => Provider.of<Dispatch<AppState>>(ctx, listen: false)(IncrementAndGetDescriptionAction());

  @override
  Widget build(BuildContext ctx) {
    return Scaffold(
        appBar: AppBar(title: const Text('Increment Example (1)')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text("You've pushed the button:"),
              Text('${counter(ctx)}', style: const TextStyle(fontSize: 30)),
              Text(description(ctx), style: const TextStyle(fontSize: 15)),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: onIncrement(ctx),
          child: const Icon(Icons.add),
        ));
  }
}

Download Details:
 

Author: marcglasberg
Download Link: Download The Source Code
Official Website: https://github.com/marcglasberg/provider_for_redux 
License: BSD-2-Clause License

#flutter 

What is GEEK

Buddha Community

Using Provider with Redux

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

Let’s use redux in react

Redux is super simple to use. Actions are used to indicate what can be possible done to the states, reducers are used to indicate the transformation of the state, dispatch is used to execute the action and store is used to combine all together. Is it sounds like greek? let me explain in detail.

What is redux?

Redux is a state management library which can be used in React and it can be also used in Angular, Vue and even vanilla JavaScript. Apart from that Context API can be used as an alternative for Redux.

Why we need redux? can’t we use states and props? This is an additional burden.

Image for post

Let me explain, If sub component has its’ own states then it is not a problem to manage them. Then what if those data is needed for the sub component two. Then we have to do **state uplifting **and pass those data to the parent component as follows and pass them to the child component as props. Then it is still manageable.

Image for post

What if those data is needed for Component One and Component Two as well. Then we have to face the problem of **props drilling **as follows because we have to pass those data here and there using props and it become a burden.

Image for post

Then redux come to solve this issue by separating the data from components as follows.

#redux-reducer #react-redux #redux #react

Sidney  Purdy

Sidney Purdy

1593513911

Use Yup with Redux-form

I wanted to replace Joiand Redux-Form with [Yup](https://github.com/jquense/yup)and [Formik](https://github.com/jaredpalmer/formik), respectively. “Now why would you want to do that!?”, you might ask. Well let’s quickly go through the reasons for Yup and Formik.

Why Yup

  1. Much lightweight than Joi.

And this is why ‘lightweight’ is important:

_tl;dr: less code = less parse/compile + less transfer + less to decompress _source

2. Easier to parse for error messages from returned error object.

3. Much flexible to customize error messages without string manipulation shenanigans.

4. Yup shares very much similar syntax and method names with Joi, making replacing Joi an easy task.

Why Formik

See “Why not Redux-Form?


However, replacing redux-form with Formik was considered to me to be a heavier task than Joi with Yup, therefore here goes ‘your friendly’ medium article about it — the gist of making Yup plays well with redux-form.

First we create a validator function that will accepts our Yup schema later.

import { Schema } from 'yup';

const validator = <T>(schema: Schema<T>) => async formValues => {
  try {
    await schema.validate(formValues, { abortEarly: false })
    return {}
  } catch (errors) {
    return errors.inner.reduce(
      (errors, err) => ({
        ...errors,
        [err.path]: err.message
      }),
      {}
    )
  }
}

export default validator

#yup #redux-form-yup #react #redux-form #programming #redux

Reduce Redux Boilerplate Code with Redux-Actions

Redux has become one of the most popular libraries in front-end development since it was introduced by Dan Abramov and Andrew Clark in 2015. They designed it as the successor for Flux, with the support of some developer tools and a few more concepts embedded in it.

Flux is a fancy name for observer pattern further modified to support React. Both Flux and Redux consist of similar concepts like Store, Actions (events in the application). In other words, Flux is a simple JavaScript object but with some middleware like redux-thunk. It can be a function or a promise for Redux. However, Redux is a single source of truth with concepts like immutability, which improve performance. It is one of the main reasons for Redux to dominate in State Management.

Image for post

Flux vs Redux comparison source: enappd.com

Despite its advantages, some developers have found it rather challenging to deal with Redux due to the amount of boilerplate code introduced with it. And the complexity of the code seems to be another reason for the difficulty.

In this article, we will look at how to reduce the boilerplate code brought about by Actions and Reducers using Redux-Actions

#react-redux-boilerplate #react-redux #react #react-actions #redux

How to Use Redux with React Hooks🔥 ( REDUX HOOKS )

Hello Friends,
In this Video, We are going to know How to use redux with react hook.
we have used redux inside Class based component with Connect() higher order component
but inside the functional based component , We couldnt use Connect!
So How can we use redux in fucntional based component ?
We will figure out it here !

Git Repository:
https://github.com/jaewonhimnae/reduxHooks-with-reactHooks

#redux #redux hooks #react hooks #react