9

I'm going through Flutter Riverpod package documentation, and for some reason the basic example in 'Getting started' is throwing Error:

Undefined class 'WidgetRef'. Try changing the name to the name of an existing class, or creating a class with the name 'WidgetRef'.

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

final helloWorldProvider = Provider((_) => 'Hello World');

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

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final String value = ref.watch(helloWorldProvider);
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text(value),
        ),
      ),
    );
  }
}

pubspec.yaml

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  flutter_riverpod: ^0.14.0+3

dev_dependencies:
  flutter_test:
    sdk: flutter
Natnael A.
  • 591
  • 6
  • 20

1 Answers1

16

In your pubspec you have specified flutter_riverpod: ^0.14.0+3, while the WidgetRef is only available from version 1.0.0 (which is currently a dev release and not a full release).

In your version of Riverpod, you can use ConsumerWidget as follows:

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

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final String value = watch(helloWorldProvider);
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text(value),
        ),
      ),
    );
  }
}

Alternatively, you could upgrade to flutter_riverpod: ^1.0.0-dev.6

TmKVU
  • 2,910
  • 2
  • 16
  • 30
  • Is `WidgetRef` the replacement for `ScopedReader`? – mLstudent33 Aug 27 '21 at 21:41
  • @mLstudent33 [It would seem so](https://pub.dev/packages/flutter_riverpod/versions/1.0.0-dev.11/changelog#100-dev0), as well as how it's referenced (from `watch()` to `ref.watch()`). – Keith DC Oct 25 '21 at 03:41