What is the difference between functions and classes to create reusable widgets?

后端 未结 5 2062
野的像风
野的像风 2020-11-22 10:20

I have realized that it is possible to create widgets using plain functions instead of subclassing StatelessWidget. An example would be this:

Widget functio         


        
5条回答
  •  心在旅途
    2020-11-22 10:59

    I've been researching on this issue for the past 2 days. I came to the following conclusion: it is OKAY to break down pieces of the app into functions. It's just ideal that those functions return a StatelessWidget, so optimisations can be made, such as making the StatelessWidget const, so it doesn't rebuild if it doesn't have to. For example, this piece of code is perfectly valid:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State {
      int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          ++_counter;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.display1,
                ),
                const MyWidgetClass(key: const Key('const')),
                MyWidgetClass(key: Key('non-const')),
                _buildSomeWidgets(_counter),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    
      Widget _buildSomeWidgets(int val) {
        print('${DateTime.now()} Rebuild _buildSomeWidgets');
        return const MyWidgetClass(key: Key('function'));
    
        // This is bad, because it would rebuild this every time
        // return Container(
        //   child: Text("hi"),
        // );
      }
    }
    
    class MyWidgetClass extends StatelessWidget {
      const MyWidgetClass({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        print('${DateTime.now()} Rebuild MyWidgetClass $key');
    
        return Container(
          child: Text("hi"),
        );
      }
    }
    

    The use of function there is perfectly fine, as it returns a const StatelessWidget. Please correct me if I'm wrong.

提交回复
热议问题