Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 943
Natnael A. Avatar asked Aug 10 '21 13:08

Natnael A.


1 Answers

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

like image 122
TmKVU Avatar answered Sep 18 '22 23:09

TmKVU