════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Tried to listen to a value exposed with provider, from outside of the widget tree.
This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.
To fix, write:
Provider.of<Counter>(context, listen: false);
It is unsupported because may pointlessly rebuild the widget associated to the
event handler, when the widget tree doesn't care about the value.
The context used was: HomePage(dependencies: [_InheritedProviderScope<Counter>], state: _HomePageState#aa95a)
'package:provider/src/provider.dart':
Failed assertion: line 262 pos 7: 'context.owner.debugBuilding ||
listen == false ||
debugIsInInheritedProviderUpdate'
When the exception was thrown, this was the stack:
#2 Provider.of (package:provider/src/provider.dart:262:7)
#3 _HomePageState.build.<anonymous closure> (package:flutter_provider_test/main.dart:42:34)
#4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
#5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
#6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#5c9f6
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(63.4, 33.0)
finalLocalPosition: Offset(63.4, 27.0)
button: 1
sent tap down
原代码如下
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'model.dart';
void main(){
runApp(ChangeNotifierProvider(
create: (_) => Counter(0),
child: MyApp())
);
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
int a = context.watch<Counter>().a;
return Scaffold(
body: Container(
child: Column(
children: [
RaisedButton(onPressed: (){
Provider.of<Counter>(context).change() ;
},child: Text('增加'),),
Text('$a'),
],
),
),
);
}
}
import 'package:flutter/material.dart';
class Counter extends ChangeNotifier{
int a;
Counter(this.a);
void change(){
this.a++;
notifyListeners();
}
}
根据错误提示,代码中监听了不该监听的值。
所以根据提示把RaisedButton
的onPressed
方法中的
Provider.of<Counter>(context).change() ;
改成
Provider.of<Counter>(context,listen: false).change() ;