Home > Net >  Why state change error occurs on flutter_riverpod during initialization
Why state change error occurs on flutter_riverpod during initialization

Time:01-04

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final dataProvider = StateNotifierProvider<DataNotifier, List<int>>((ref) {
  return DataNotifier();
});

class DataNotifier extends StateNotifier<List<int>> {
  DataNotifier() : super([]);

  Future<void> getData() async {
    state = [];
    await Future.delayed(const Duration(seconds: 2));
    state = [1, 2];
  }
}

void main() => runApp(ProviderScope(child: App()));

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: Center(
          child: ElevatedButton(
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(builder: (_) => SecondPage()),
              );
            },
            child: const Text('Next page'),
          ),
        ),
      ),
    );
  }
}

class SecondPage extends ConsumerStatefulWidget {
  const SecondPage({Key? key}) : super(key: key);

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

class _SecondPageState extends ConsumerState<SecondPage> {
  @override
  void initState() {
    super.initState();
    ref.read(dataProvider.notifier).getData();
  }

  @override
  Widget build(BuildContext context) {
    final numbers = ref.watch(dataProvider);
    return Scaffold(
      appBar: AppBar(),
      body: ListView.builder(
        itemBuilder: (_, index) {
          return Text('data: $index');
        },
        itemCount: numbers.length,
      ),
    );
  }
}

I am new to riverpod and I noticed this error while changing state.

In the above code when I tap the "next page" button at the fresh start for the first time it works as expected but when I go back and again tap the "next page" button, an error shown below is thrown:

StateNotifierListenerError (At least listener of the StateNotifier Instance of 'DataNotifier' threw an exception
when the notifier tried to update its state.

Does anyone know why this occurs and how can I prevent it.

CodePudding user response:

You can solve the issue using autoDispose

final dataProvider = StateNotifierProvider.autoDispose<DataNotifier, List<int>>(
  (ref) => DataNotifier(),
);

For Future I prefer using FutureProvider.

More about riverpod

  • Related