我正在研究抖动,最近我建立了这个非常简单的灯泡示例(Problems while using Flutter Provider package)。
我意识到,任何应用程序都可以将Consumer和Stateless窗口小部件与提供所有这些DataModels的主Home应用程序一起使用,完全跳过Stateful窗口小部件。这是一个小例子
class Data with ChangeNotifier {
bool isOn = false;
void toggle() {
this.isOn = !this.isOn;
notifyListeners();
}
}
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("main app");
return ChangeNotifierProvider<Data>(
create: (context) => Data(),
child: MaterialApp(
home: Home(),
),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("home");
return Consumer<Data>(
builder: (context , data , child) => Scaffold(
appBar: AppBar(),
backgroundColor:
data.isOn ? Colors.yellow[100] : Colors.black,
body: Center(
child: Column(
children: <Widget>[
Stick(),
Bulb(),
Switch()
],
),
),
),
);
}
}
class Bulb extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("bulb");
return Consumer<Data>(
builder: (context , data , child) => 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)),
boxShadow: data.isOn? <BoxShadow>[BoxShadow(spreadRadius: 5,color: Colors.orange , blurRadius: 100)] : null,
color: data.isOn ? Colors.yellow : Colors.white,
),
child: GestureDetector(
onTap: () {
data.toggle();
},
),
),
);
}
}
如此说来,我是否断定提供者和无状态小部件可以完全替代有状态小部件?如果是这样,这样做是个好主意吗?
还请建议使用状态控件和提供程序的位置。
感谢您的时间和对此的想法。
最佳答案
是的,绝对可以用提供者和无状态小部件替换有状态小部件。您要使用提供程序或有状态窗口小部件完全取决于您。
在我的建议中,如果您的有状态小部件不大,并且在该小部件中您不经常调用setstate,那么最好使用有状态小部件,因为通过在其中添加提供者,您最终将创建更多样板代码。
因此,我建议您在页面代码很大并且想要将代码分为几部分时使用提供程序。
除此之外,我想提请注意消费者的 child 属性(property)。消费者的子窗口小部件在数据更改时不会重建,因此您也可以使用它。
关于flutter - 在flutter中使用有状态小部件的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61538796/