在 flutter 中使用有状态小部件的替代方法

Alternate approach of using stateful widgets in flutter

我正在研究 flutter,最近我构建了这个非常简单的灯泡示例 ()。

我意识到任何应用程序都可以使用 Consumer 和 Stateless 小部件,主应用程序提供所有这些 DataModels ,完全跳过 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 和无状态小部件可以完全替代有状态小部件的结论是否正确?如果是这样,这样做是个好主意吗?

还请建议使用有状态小部件和提供程序的地方。

感谢您抽出宝贵时间对此发表看法。

是的,您绝对可以用提供程序和无状态小部件替换有状态小部件。您要使用提供程序还是有状态小部件完全取决于您。

根据我的建议,如果您的有状态小部件不大,并且在该小部件中您不经常调用 setstate,那么最好使用有状态小部件,因为通过在其中添加提供程序,您最终会创建更多样板代码。

所以,当你的页面代码很大并且你想将代码分成几个部分时,我建议你使用提供程序。

除此之外,我想提请注意 child 属性 消费者。 Childconsumer的widget不会在数据变化时重建,所以你也可以使用。