'Error in read context.read(incrementProvider).increment();
Error in read context.read(incrementProvider).increment();
Can someone help me? i tried ref.read but its turn red
Error in read context.read(incrementProvider).increment();
Can someone help me? i tried ref.read but its turn red
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(
const ProviderScope(child: MyApp()),
);
}
class IncrementNotifier extends ChangeNotifier {
int _value = 0;
int get value => _value;
void increment() {
_value++;
notifyListeners();
}
}
final incrementProvider = ChangeNotifierProvider((ref) => IncrementNotifier());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Riverpod Tutorial',
home: Scaffold(
appBar: AppBar(
title: Text('Riverpod Tutorial'),
),
body: Center(
child: Consumer(
builder: (context, ref, child) {
final incrementNotifier = ref.watch(incrementProvider);
return Text(incrementNotifier.value.toString());
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
context.read(incrementProvider).increment();
},
child: Icon(Icons.add),
),
),
);
}
}
Solution 1:[1]
In flutter_riverpod: ^1.0.3, you have to use ref instead of context.
Try to wrap your floatingActionButton with Consumer and then use ref to read the provider.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Riverpod Tutorial',
home: Scaffold(
appBar: AppBar(
title: Text('Riverpod Tutorial'),
),
body: Center(
child: Consumer(
builder: (context, ref, child) {
final incrementNotifier = ref.watch(incrementProvider);
return Text(incrementNotifier.value.toString());
},
),
),
floatingActionButton: Consumer(
builder: (context, ref, child) {
return FloatingActionButton(
onPressed: () {
ref.read(incrementProvider).increment();
},
child: Icon(Icons.add),
);
},
),
),
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
