简体   繁体   English

在 Flutter 的扩展内访问 Riverpod 的 state 提供程序的正确方法?

[英]Proper way to access Riverpod's state provider inside extensions in Flutter?

How to access counterProvider inside extension?如何在扩展内访问counterProvider

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

main() {
  runApp(const ProviderScope(child: MyApp2()));
}

class MyApp2 extends ConsumerWidget {
  const MyApp2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final watchCounter = ref.watch(counterProvider);
    return MaterialApp(
      home: Scaffold(
        body: Text('$watchCounter'),
        floatingActionButton: FloatingActionButton(
          child: const Icon(Icons.add),
          onPressed: () {
            ref.read(counterProvider.notifier).adder();
          },
        ),
      ),
    );
  }
}

class CounterNotifier extends StateNotifier<int> {
  CounterNotifier() : super(0);
  int counter = 0;

  void adder() {
    state = ++counter;
  }
}

final counterProvider = StateNotifierProvider<CounterNotifier, int>(
  (ref) => CounterNotifier(),
);



extension StringExtension on String {
  String AddPrefix(){
    //                    <---***--- How to access counterProvider here?
    
    return '#$this';
  }
}

You can pass it as a parameter to the AddPrefix() function.您可以将其作为参数传递给AddPrefix() function。

Send to addPrefix() extension with function params.使用 function 参数发送到 addPrefix() 扩展。

extension StringExtension on String {
  String addPrefix(String prefix){
    return prefix + ' #$this';
  }
}

Text('$watchCounter'.addPrefix("test")) // test 0

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

相关问题 Flutter riverpod 提供程序未在 UI 中更新 state - Flutter riverpod provider not updating state in UI Flutter Riverpod/Provider:为 stateNotifier 设置初始 state - Flutter Riverpod/Provider: Setting an initial state for a stateNotifier 未来的供应商不会读取riverpod state 供应商| Flutter - Future provider doesn't read a riverpod state provider | Flutter 你如何在 Riverpod 中创建和修改一个用于 flutter 的布尔状态提供者? - How do you create and modify a boolean state provider in riverpod for flutter? 使用 Flutter Riverpod 清除所有缓存数据、监听器、提供者状态 - Clear all cache data, listener, state of provider using Flutter Riverpod 如何在 riverpod 未来提供程序中抛出错误并在错误 flutter 中捕获它 - How to throw error inside riverpod future provider and catch it on error flutter 为什么 Riverpod 提供商在已经有价值的情况下进入加载 state? - Why Riverpod provider goes into the loading state when there's already value? (Flutter / Riverpod)在任何情况下都不应该在 Riverpod 的提供者体内使用 ProviderReference.read 吗? - (Flutter / Riverpod) Should not ProviderReference.read inside the body of a provider at Riverpod be used in any case? Riverpod 条件提供者状态更新 - riverpod conditional provider state updates Flutter 与 provider 和 riverpod 做一个表格 - Flutter make a form with provider and riverpod
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM