skip to Main Content

Here is my Custom reusable Widget code.

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

class MyFloatingActionButton extends ConsumerWidget {
  final Function(ProviderRef ref) onPressed;

  MyFloatingActionButton(this.onPressed);


  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return FloatingActionButton(
      onPressed: () => onPressed,
      tooltip: 'Increment',
      child: Icon(Icons.add),
    );
  }
}

Here is the the parent widget :

floatingActionButton: MyFloatingActionButton((ref) => ref.read(myProvider)._increase())

Here is myProvider

class CountNotifier extends ChangeNotifier {
  int num = 0;
  void _increase() {
    num ++;
    notifyListeners();
  }
}
final myProvider = ChangeNotifierProvider((ref) {
  return CountNotifier();
});

After passinging the Function to its child its not working anymore. But in the parent widget it just working fine.

I am expecting to pass ref.read() function to any child widget.

2

Answers


  1. Your callback function won’t be called as your code:

    FloatingActionButton(
      onPressed: () => onPressed,
      tooltip: 'Increment',
      child: Icon(Icons.add),
    );
    

    Because () => onPressed means a function always returns a value, and the value is your callback function. You have never called your callback function!

    So you should call it like this: () => onPress(ref).

    I don’t know what you want to implement, but my suggestion is just only to use the ref from the parent widget, don’t pass the ref by hand.

    Login or Signup to reply.
  2. Try it like this:

    // parent:
    floatingActionButton: MyFloatingActionButton(ref.read(myProvider)._increase)
    

    child:

    class MyFloatingActionButton extends ConsumerWidget {
      const MyFloatingActionButton(this.onPressed);
    
      final Function() onPressed;
    
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        return FloatingActionButton(
          onPressed: onPressed,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search