【发布时间】:2023-03-11 07:37:01
【问题描述】:
我正在探索 Flutter,最近我构建了这个非常简单的灯泡示例 (Problems while using Flutter Provider package)。
我意识到任何应用程序都可以将 Consumer 和 Stateless 小部件与提供所有这些 DataModel 的主 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();
},
),
),
);
}
}
话虽如此,我是否正确得出结论,Provider 和无状态小部件可以完全取代有状态小部件?如果是这样,这样做是个好主意吗?
还请建议使用有状态小部件的位置以及使用提供程序的位置。
感谢您的时间和想法。
【问题讨论】: