繁体   English   中英

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

[英]Alternate approach of using stateful widgets in flutter

我正在探索 flutter,最近我构建了这个非常简单的灯泡示例( 使用 Flutter 提供程序 package 时出现问题)。

我意识到任何应用程序都可以将消费者和无状态小部件与提供所有这些数据模型的主主页应用程序一起使用,完全跳过有状态小部件。 这是一个小例子

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,那么最好使用有状态小部件,因为通过在其中添加提供程序,您最终会创建更多样板代码。

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

除此之外,我想提请注意消费者的儿童财产。 消费者的子小部件在数据发生变化时不会重建,因此您也可以使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM