【flutter】flutter的provider调用是报错
问题描述
简单计数器例子,想用flutter的provider实现
class CartPage extends StatelessWidget {@override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
child: Column(
children: <Widget>[
Number(),
MyButton()
],
),
)
);
}
}
class Number extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top:200),
child: Provide<Counter>(
builder: (context,child,counter){
return Text(
'${counter.value}',
style: Theme.of(context).textTheme.display1,
);
},
),
);
}
}
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child:RaisedButton(
onPressed: (){
Provide.value<Counter>(context).increment();
},
child: Text('递增'),
)
);
}
}
// provider文件
import 'package:flutter/material.dart';
class Counter with ChangeNotifier {
int value =0 ;
increment(){
value++;
notifyListeners();
}
}
// main
void main(){
var counter =Counter();
var providers =Providers();
providers
..provide(Provider<Counter>.value(counter));
runApp(ProviderNode(child:MyApp(),providers:providers));
}
问题出现的环境背景及自己尝试过哪些方法
但是会报错
/ (This is taking an unexpectedly long time.)I/flutter (26528): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞════════════════════════════════════════════════════
═══════
I/flutter (26528): The following NoSuchMethodError was thrown building Provide<Counter>(dirty):
I/flutter (26528): The method 'getValue' was called on null.
I/flutter (26528): Receiver: null
你期待的结果是什么?实际看到的错误信息又是什么?
回答
用大R刷新一遍就出来了,改变runApp节点什么的,需要强制刷新,改UI就不用,希望帮到你, 我刚刚也遇到这个问题
以上是 【flutter】flutter的provider调用是报错 的全部内容, 来源链接: utcz.com/a/84081.html