Natnael A.
Natnael A.

Reputation: 628

Dart Riverpod: Undefined class 'WidgetRef'

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

Upvotes: 10

Views: 4053

Answers (1)

TmKVU
TmKVU

Reputation: 3000

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

Upvotes: 18

Related Questions