I have a serious problem in Flutter with Riverpod. I am just starting to learn it, but I am encountering errors with every .state
, and no AI has been able to help me solve the problem.
Here is the complete code:
// my_button_widget.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final buttonSelectedProvider = StateProvider<bool>((ref) => false);
class MyButtonWidget extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(
title: Text('Riverpod Button Example'),
),
body: Center(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed))
return Colors.orange;
return ref.watch(buttonSelectedProvider).state //error in .state
? Colors.orange
: Colors.white; // Use the component's default.
},
),
),
onPressed: () {
ref.read(buttonSelectedProvider).state = //error in .state
!ref.read(buttonSelectedProvider).state; //error in .state
},
child: Text('Press me'),
),
),
);
}
}
The suggestion from VS Code is as follows:
The getter 'state' isn't defined for the type 'bool'. Try importing the library that defines 'state', correcting the name to the name of an existing getter, or defining a getter or field named 'state'.dartundefined_getter Type: InvalidType
My version of Riverpod in pubspec.yaml
is: flutter_riverpod: ^2.4.9
."
From the changelog:
Deprecated StateProvider.state Instead, use either ref.watch(stateProvider) or ref.read(stateProvider.notifier).state =
And avoid legacy riverpod tools. In brief, avoid legacy ChangeNotifier, StateNotifier (and their providers) and StateProvider. Use only Provider, FutureProvider, StreamProvider, and Notifier, AsyncNotifier, StreamNotifier (and their providers).