1

How to access counterProvider inside extension?

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';
  }
}
Davoud
  • 2,576
  • 1
  • 32
  • 53

2 Answers2

1

You can pass it as a parameter to the AddPrefix() function.

Ruble
  • 2,589
  • 3
  • 6
  • 29
-1

Send to addPrefix() extension with function params.

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

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