Dart Riverpod:未定义 class 'WidgetRef'
Dart Riverpod: Undefined class 'WidgetRef'
我正在浏览 Flutter Riverpod 包文档,出于某种原因 'Getting started' 中的基本 example 抛出错误:
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
在您的 pubspec 中您指定了 flutter_riverpod: ^0.14.0+3
,而 WidgetRef
仅适用于版本 1.0.0(目前是开发版本而非完整版本)。
在您的 Riverpod 版本中,您可以按如下方式使用 ConsumerWidget:
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),
),
),
);
}
}
或者,您可以升级到 flutter_riverpod: ^1.0.0-dev.6
我正在浏览 Flutter Riverpod 包文档,出于某种原因 'Getting started' 中的基本 example 抛出错误:
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
在您的 pubspec 中您指定了 flutter_riverpod: ^0.14.0+3
,而 WidgetRef
仅适用于版本 1.0.0(目前是开发版本而非完整版本)。
在您的 Riverpod 版本中,您可以按如下方式使用 ConsumerWidget:
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),
),
),
);
}
}
或者,您可以升级到 flutter_riverpod: ^1.0.0-dev.6