简体   繁体   English

如何在 Riverpod state 管理中使用读取方法

[英]how to use read method with riverpod state management

i use riverpod state management我使用riverpod state管理

pubspec.yaml: 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'在 setState 中,我在读取方法中有error :未为类型“BuildContext”定义方法“读取”。尝试将名称更正为现有方法的名称,或定义名为“读取”的方法

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 :我在useProvider中有Error

The method 'useProvider' isn't defined for the type 'Conter2'.没有为“Conter2”类型定义方法“useProvider”。 Try correcting the name to the name of an existing method, or defining a method named 'useProvider'尝试将名称更正为现有方法的名称,或定义名为“useProvider”的方法

Does anyone know what is the solution to this 2Error?有谁知道这个 2Error 的解决方案是什么?

You should add 'flutter_riverpod' package because you are using flutter.您应该添加“flutter_riverpod”package,因为您使用的是 flutter。 If you are going to use hooks, add 'hooks_riverpod'.如果您要使用钩子,请添加“hooks_riverpod”。

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

In your main.dart, wrap your MaterialApp with ProviderScope.在您的 main.dart 中,使用 ProviderScope 包装您的 MaterialApp。

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

You have many ways to read a StateProvider, just to mention:您有很多方法可以读取 StateProvider,仅提一下:

  • Using ConsumerWidget (for StatelessWidgets)使用 ConsumerWidget(对于 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使用 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我强烈建议您阅读文档并查看所有提供的示例: https://riverpod.dev/docs/concepts/reading

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM