Riverpod UncontrolledProviderScope

Created At: 2023-08-23 23:01:22 Updated At: 2024-04-17 14:13:50

Riverpod UncontrolledProviderScope is special widget and that helps you prevent rebuild of your widget.

Prevent unnecessary rebuild of wiget may help performance optimize. In general, Flutter cause a lot of rebuild of widget even if it's not meant to rebuild or you just don't need to rebuild. 

Let's take an example of our counter app. In general counter app increases the value as you click on a button. But the below example won't do it.


import 'package:flutter/material.dart';

import 'package:flutter_riverpod/flutter_riverpod.dart';


final counterProvider = StateProvider((ref) => 0);


void main() {

runApp(

ProviderScope(

child: MaterialApp(

home: MyApp(),

),

),

);

}

final provider = ProviderContainer();

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {


return Scaffold(

appBar: AppBar(

title: Text('Counter App'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

CounterDisplay(),

UncontrolledProviderScope(

container: provider,

child: CounterButton(),

),

],

),

),

);

}

}


class CounterDisplay extends ConsumerWidget {

@override

Widget build(BuildContext context, WidgetRef ref) {

final count = ref.watch(counterProvider);

print(count);

return Text(

'Count: $count',

style: TextStyle(fontSize: 24),

);

}

}


class CounterButton extends ConsumerWidget {

@override

Widget build(BuildContext context, WidgetRef ref) {

//final count = ref.watch(counterProvider).state;

//var counter = ref.read(counterProvider.notifier).state++;


return ElevatedButton(

onPressed: () {

// Manually increment the counter without triggering immediate rebuild.

var x =ref.watch(counterProvider.notifier).state++;

print(x);

},

child: Text('Increment'),

);

}

}

In the above example we have wrapped CounterButton() widget using UncontrolledProviderScope(). Because of this even if you  click on the increment button, we don't see any value updated on the screen. Of course you will print log on the console that counter value has increased. 

If you remove UncontrolledProviderScope() you will see that we counter value is increasing regularly as you press on the button.The only condition for using UncontrolledProviderScope() you have to provide it ProviderContainer() instance.

UncontrolledProviderScope could be interesting. If you have unnecessary rebuild of widget in a loop it throws error. It will show Stack Overflow issue.

Here you have a link to read more about UncontrolledProviderScope and StackOverFlow error here.

Learn more advanced Riverpod concept here

Comment

Add Reviews