This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Flutter Riverpod – Part 2


Within the final blog, we discovered to arrange Riverpod for a Flutter Undertaking and easy methods to use the fundamental of all Riverpod Supplier, the Supplier(). On this weblog we’ll study to make use of probably the most helpful and fundamental Supplier, the StateProvider().



Let’s dig into why do we want a Supplier?

As an example you may have an A Flutter(Riverpod) Undertaking with the next code

import 'bundle:flutter/materials.dart';
import 'bundle:flutter_riverpod/flutter_riverpod.dart';

int counter = 0;

void foremost() {
  runApp(
    const ProviderScope(
      baby: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : tremendous(key: key);

  @override
  Widget construct(BuildContext context) {
    return MaterialApp(
      title: 'Riverpod',
      theme: ThemeData(
        primarySwatch: Colours.blue,
      ),
      residence: const MyHomePage(title: 'Flutter Riverpod'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : tremendous(key: key);

  ultimate String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget construct(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Textual content(widget.title),
      ),
      physique: Heart(
        baby: Column(
          mainAxisAlignment: MainAxisAlignment.heart,
          youngsters: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            const CounterCard()
          ],
        ),
      ),
    );
  }
}

class CounterCard extends StatefulWidget {
  const CounterCard({
    Key? key,
  }) : tremendous(key: key);

  @override
  State<CounterCard> createState() => _CounterCardState();
}

class _CounterCardState extends State<CounterCard> {
  void _incrementCounter() {
    setState(() {
      counter++;
    });
  }

  @override
  Widget construct(BuildContext context) {
    return Card(
        baby: ListTile(
      title: Textual content("$counter"),
      trailing: IconButton(
        icon: const Icon(Icons.plus_one),
        onPressed: _incrementCounter,
      ),
    ));
  }
}


Enter fullscreen mode

Exit fullscreen mode

Whats all this Supplier Scope? Learn my previous blog on organising Riverpod on your Undertaking!

So what is going on on within the code above?
Its the same Default Flutter Counter Utility that we get after we create a brand new Flutter Undertaking, however with Riverpod and a few Adjustments to show the issue with state.
We now have a world variable int counter which is initialised to Zero. Then that counter is used at two locations, one within the higher MyHomePage Class and second in CounterCard Class. Within the CounterCard, there’s an IconButton with the perform _incrementCounter() which increments the counter variable. Now Ideally, on urgent the button, we must always see the counter getting incremented at each the locations. However this does not occur. It is because the setState() methodology solely refreshes the CounterCard Contents and never of MyHomePage. Flutter State works on this approach to enhance efficiency, think about the whole display refreshing everytime for small modifications and you do not personal an M1 Gadget. To unravel this drawback now we have State Administration Options. Let’s determine all of it out utilizing some diagrams!! Who would not love diagrams proper?

Instagram post - 1.png
Instagram post - 2.png

So if you wish to change the state of a base class from a derived class(which occurs fairly continuously), it turns into fairly tedious, we’re gonna resolve this drawback with Riverpod, extra particularly with a Supplier that comprises state or StateProvider().

So now we have a counter variable proper? We’re going to convert it into Supplier simply how we discovered within the previous blog.

//int counter = 0; This Adjustments to
ultimate counterProvider = Supplier<int>((ref) {
  return 0;
});
Enter fullscreen mode

Exit fullscreen mode

And half the Magic is Completed!!

Change the MyHomePage to a Stateless Widget…

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key, required this.title}) : tremendous(key: key);

  ultimate String title;

  @override
  Widget construct(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Textual content(title),
      ),
      physique: Heart(
        baby: Column(
          mainAxisAlignment: MainAxisAlignment.heart,
          youngsters: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            const CounterCard()
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode

Exit fullscreen mode

Once more cahnge the MyHomePage to a ConsumerWidget identical to we discovered within the previous blog and let the Textual content Widget watch the counterProvider()


class MyHomePage extends ConsumerWidget {
  const MyHomePage({Key? key, required this.title}) : tremendous(key: key);

  ultimate String title;

  @override
  Widget construct(BuildContext context,WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(
        title: Textual content(title),
      ),
      physique: Heart(
        baby: Column(
          mainAxisAlignment: MainAxisAlignment.heart,
          youngsters: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              ref.watch(counterProvider).toString(),
              style: Theme.of(context).textTheme.headline4,
            ),
            const CounterCard()
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode

Exit fullscreen mode

Now typically you’ll want to learn a supplier from a StatefulWidget, and we do that utilizing ConsumerStatefulWidget which we’ll do to the CounterCard StatefulWidget.

// Add Client to StatefulWidget
class CounterCard extends ConsumerStatefulWidget {
  const CounterCard({
    Key? key,
  }) : tremendous(key: key);

  @override
//    Adjustments right here 
  ConsumerState<CounterCard> createState() => _CounterCardState();
}
//    Adjustments right here 
class _CounterCardState extends ConsumerState<CounterCard> {
 ...
}
Enter fullscreen mode

Exit fullscreen mode

And that is it!
Now bear in mind earlier than I talked a few completely different sort of Supplier and it was the StateProvider, it mainly is an a Supplier however it may preserve the State of its contents.
Now go above and add State to the counterProvider

//                                    Over Right here
ultimate counterProvider = StateProvider<int>((ref) {
  return 0;
});
Enter fullscreen mode

Exit fullscreen mode

Now go to CounterCard and let the Textual content watch the counterProvider

class _CounterCardState extends ConsumerState<CounterCard> {


  @override
  Widget construct(BuildContext context) {
    return Card(
        baby: ListTile(
      title: Textual content(ref.watch(counterProvider).toString()),
      trailing: IconButton(
        icon: const Icon(Icons.plus_one),
        onPressed: (){
          ...
        },
      ),
    ));
  }
}

Enter fullscreen mode

Exit fullscreen mode

Now within the onPressed now we have to increment the “state” of counterProvider.
To do that we use ref.learn() as a substitute of ref.watch, so right here it must be,

onPressed: () {
          setState(() {
            ref.learn(counterProvider.state).state++;
          });
        },
Enter fullscreen mode

Exit fullscreen mode

Be aware that right here it can nonetheless work in case you do not use a setState Operate.
That is it and now run this system to resolve the State Mangement Downside we confronted earlier.

I will likely be quickly beginning a Riverpod Collection on Youtube so do not forget to subscribe my Youtube Channel and Additionally comply with me on Twitter and Instagram to get the most recent updates and Suggestions and Tips utilizing Flutter.



The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?