What color system does flutter use and why do we use `const Color` instead of `new Color`

前端 未结 3 1846
鱼传尺愫
鱼传尺愫 2020-12-06 12:11

Today I came over following snippet of code that implements gradient in flutter

return new Container(
  ...
  decoration: new BoxDecoration(
    gradient: ne         


        
3条回答
  •  醉酒成梦
    2020-12-06 12:21

    When we use setState() Flutter calls the build method and rebuilds every widget tree inside it. The best way to avoid this is by using const costructors.

    Use const constructors whenever possible when building your own widgets or using Flutter widgets. This helps Flutter to rebuild only widgets that should be updated

    So if you have a StatefulWidget and you are using setState((){}) to update that widget and you have widgets like:

    class _MyWidgetState extends State {
    
      String title = "Title";
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(title),
          ),
          body: Column(
            children: [
              const Text("Text 1"),
              const Padding(
                padding: const EdgeInsets.all(8.0),
                child: const Text("Another Text widget"),
              ),
              const Text("Text 3"),
            ],
          ),
          floatingActionButton: FloatingActionButton(
            child: const Icon(Icons.add),
            onPressed: () {
              setState(() => title = 'New Title');
            },
          ),
        );
      }
    }
    

    If you run this code and press the floating action button, all the widgets defined as const won't get rebuilded.

    For more info: const constructors

提交回复
热议问题