Home > Back-end >  how to use read method with riverpod state management
how to use read method with riverpod state management

Time:01-01

i use riverpod state management

pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  provider: ^6.0.1
  get: ^4.6.1
  flutter_bloc: ^8.0.1
  riverpod: ^1.0.3
  hooks_riverpod: ^1.0.3

my provider file

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

class CounterRiv extends StateNotifier<int> {
  CounterRiv() : super(0);

  void increament() => state  ;
}

and this is main

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:statemng/riverpod/controler_riv.dart';
import 'package:statemng/riverpod/home_riv.dart';


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(),
      
      home: ProviderScope(
        child: MyHomeRiv(),
      ),
    );
  }
}

file home

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

import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:statemng/riverpod/controler_riv.dart';

import 'dashboard_riv.dart';

class MyHomeRiv extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

final counterprovider =
    StateNotifierProvider<CounterRiv, int>((ref) => CounterRiv());

class _MyHomePageState extends State<MyHomeRiv> {
  @override
  int n = 0;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("state management"),
      ),
      body: Center(
          child: Column(
        children: [
          Dashboard(),
        ],
      )),
      floatingActionButton:  FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: () {
              print("n= ${n  }");

              setState(() {
                context.read(counterprovider.notifier).increament();
              });
            }),
      
    );
  }
}

in setState i have error in read method :The method 'read' isn't defined for the type 'BuildContext'.Try correcting the name to the name of an existing method, or defining a method named 'read'

in counter file

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

import 'package:statemng/riverpod/home_riv.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class Conter2 extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final count = useProvider(counterprovider);
    return Card(
      elevation: 6,
      child: Container(
        height: 150,
        width: 150,
        child: Center(
          child: Text(count .toString(), style: const TextStyle(fontSize: 60)),
        ),
      ),
    );
  }
}

i have Error in useProvider :

The method 'useProvider' isn't defined for the type 'Conter2'. Try correcting the name to the name of an existing method, or defining a method named 'useProvider'

Does anyone know what is the solution to this 2Error?

CodePudding user response:

You should add 'flutter_riverpod' package because you are using flutter. If you are going to use hooks, add 'hooks_riverpod'.

Check this table: https://riverpod.dev/docs/getting_started#installing-the-package

In your main.dart, wrap your MaterialApp with ProviderScope.

void main() {
  runApp(ProviderScope(child: MyApp()));
}

You have many ways to read a StateProvider, just to mention:

  • Using ConsumerWidget (for StatelessWidgets)
class MyHomeRiv extends ConsumerWidget { 
  const HomeView({Key? key}): super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(
        title: Text("state management"),
      ),
      body: Center(
          child: Column(
          children: [
           Dashboard(),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
             ref.read(counterprovider.notifier).increament();
          },
       ),
    );
  }
}
  • Using HookConsumerWidget
class Conter2 extends HookConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterprovider);
    return Card(
      elevation: 6,
      child: Container(
        height: 150,
        width: 150,
        child: Center(
          child: Text(count.toString()),
        ),
      ),
    );
  }
}

I strongly recommend you to read the documentation and see all the provided examples: https://riverpod.dev/docs/concepts/reading

  • Related