[英]Problems while using Flutter Provider package
我正在创建一个非常简单的应用程序来练习 flutter 提供者 package。 该应用程序有一个灯泡,单击时应使用提供程序更改其背景和屏幕背景。 但这似乎不起作用。 TBH 这很令人困惑
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MainApp());
class Data extends ChangeNotifier{
bool isOn = false;
void toggle(){
this.isOn = !this.isOn;
notifyListeners();
print("new value is $isOn");
}
}
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<Data>(
create: (context) => Data(),
child: MaterialApp(
home: Home(),
),
);
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
backgroundColor: Provider.of<Data>(context).isOn ? Colors.yellow[100] : Colors.black,
body: Center(
child: Column(
children: <Widget>[
Stick(),
Bulb(),
],
),
),
);
}
}
class Stick extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: 150,
width: 40,
color: Colors.brown,
);
}
}
class Bulb extends StatefulWidget {
@override
_BulbState createState() => _BulbState();
}
class _BulbState extends State<Bulb> {
@override
Widget build(BuildContext context) {
return Container(
height: 200,
width: 250,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(100),
topRight: Radius.circular(100),
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30)),
color: Provider.of<Data>(context).isOn ? Colors.yellow : Colors.white,
),
child: GestureDetector(
onTap: (){
Provider.of<Data>(context).toggle();
setState(() {
});
},
),
);
}
}
树结构有一个主应用程序,其中包含一个 Home 应用程序,其中包含 2 个其他小部件,一个容器内的棒和一个灯泡。 单击灯泡时,我正在尝试更新灯泡的背景和 Home 小部件。 灯泡有一个手势检测器任何类型的提示或帮助表示赞赏
尝试在提供者调用中添加listen: false
:
Provider.of<Data>(context, listen: false).toggle();
问题是因为Provider
构造函数有一个命名参数listen
,默认情况下它等于true
。 当您使用Provider.of()
方法时,这种行为会强制重建。 在当前的构建仍处于活动状态时调用build
是不可能的。 这就是为什么您建议将listen
设置为false
的原因,因为它会禁用默认行为。
最好像这样实现:
...
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Consumer<Data>(
builder: (_, data, __) {
return Scaffold(
appBar: AppBar(),
backgroundColor: data.isOn ? Colors.yellow[100] : Colors.black,
body: Center(
child: Column(
children: <Widget>[
Stick(),
Bulb(),
],
),
),
);
}
);
}
}
...
class _BulbState extends State<Bulb> {
@override
Widget build(BuildContext context) {
return Consumer<Data>(
builder: (_, data, __) {
return Container(
height: 200,
width: 250,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(100),
topRight: Radius.circular(100),
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30)
),
color: data.isOn ? Colors.yellow : Colors.white,
),
child: GestureDetector(
onTap: () {
data.toggle();
setState(() {});
},
),
);
},
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.