Riverpod UncontrolledProviderScope

Riverpod UncontrolledProviderScope

    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. 

    import 'package:flutter/material.dart';
    import 'package:flutter_riverpod/flutter_riverpod.dart';
    
    final counterProvider = StateProvider<int, int>((ref) => 0);
    
    void main() {
      runApp(
        ProviderScope(
          child: MaterialApp(
            home: MyApp(),
          ),
        ),
      );
    }
    
    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: <Widget>[
                CounterDisplay(),
                UncontrolledProviderScope(
                  child: CounterButton(),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    class CounterDisplay extends ConsumerWidget {
      @override
      Widget build(BuildContext context, ScopedReader watch) {
        final count = watch(counterProvider).state;
        return Text(
          'Count: $count',
          style: TextStyle(fontSize: 24),
        );
      }
    }
    
    class CounterButton extends ConsumerWidget {
      @override
      Widget build(BuildContext context, ScopedReader watch) {
        final count = watch(counterProvider).state;
        final counter = context.read(counterProvider);
    
        return ElevatedButton(
          onPressed: () {
            // Manually increment the counter without triggering immediate rebuild.
            counter.state++;
          },
          child: Text('Increment'),
        );
      }
    }

    UncontrolledProviderScope could be interesting. If you have unnecessary rebuild of widget in a loop it throws error

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

    Courses


    Recommended posts


    Recent posts