首页 > 解决方案 > Flutter/Dart 基本理解

问题描述

很抱歉用这个问题打扰你。但我试图重新开始编程,但我无法得到以下内容(来自颤振的代码示例)

class MyAppBar extends StatelessWidget {
  MyAppBar({this.title});

  // Fields in a Widget subclass are always marked "final".

  final Widget title;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 56.0, // in logical pixels
      padding: const EdgeInsets.symmetric(horizontal: 8.0),
      decoration: BoxDecoration(color: Colors.blue[500]),
      // Row is a horizontal, linear layout.
      child: Row(
        // <Widget> is the type of items in the list.
        children: <Widget>[
          IconButton(
            icon: Icon(Icons.menu),
            tooltip: 'Navigation menu',
            onPressed: null, // null disables the button
          ),
          // Expanded expands its child to fill the available space.
          Expanded(
            child: title,
          ),
          IconButton(
            icon: Icon(Icons.search),
            tooltip: 'Search',
            onPressed: null,
          ),
        ],
      ),
    );
  }
}

class MyScaffold extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Material is a conceptual piece of paper on which the UI appears.
    return Material(
      // Column is a vertical, linear layout.
      child: Column(
        children: <Widget>[
          MyAppBar(
            title: Text(
              'Example title',
              style: Theme.of(context).primaryTextTheme.title,
            ),
          ),
          Expanded(
            child: Center(
              child: Text('Hello, world!'),
            ),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    title: 'My app', // used by the OS task switcher
    home: MyScaffold(),
  ));
}

所以我脑子里有几个问题,有些答案我只是不知道它们是否属实。因此,如果我能帮助我并纠正我,那就太好了。

  1. 在 MyAppBar 类的开头

    类 MyAppBar 扩展 StatelessWidget { MyAppBar({this.title});

    // Widget 子类中的字段总是被标记为“final”。

    最终的小部件标题;

为什么这是必要的?我们是否“告诉”每次调用这个小部件时都会传递一个标题(并且标题是一个小部件)?

  1. 从 MyScaffold 调用同一个 Widget 背后的逻辑是什么(我知道,逻辑是你可以更改标题等)。是不是就像我们用另一个 Column Widget 构建 Widget,然后将 MyAppBar 传递给 Column Widget ?如果是,小部件如何知道,从 MyAppBar-Widget 可以期待什么

    return Material( // Column 是垂直的线性布局。 child: Column( children: [ MyAppBar( title : Text( 'Example title',

(为什么知道标题是“已搜索”)

是不是它只需要一个标题的原因是我们写的

MyAppBar({this.title});

在一开始的时候 ?

如果我要在 MyAppBar 中写,我是对的吗

MyAppBar({this.title});
MyAppNumber({this.number});

每次调用小部件时,它都需要 2 个输入?

希望我的问题可以理解,非常感谢您的帮助!!!

来源:https ://flutter.dev/docs/development/ui/widgets-intro

也许更容易阅读

编辑:或者我怎么能在另一个 AppBar 下方添加另一个 AppBar,也许我理解它比更好。

标签: dartflutter

解决方案


  1. 所有字段都标记为 final,因为该类是不可变的,因此根据定义,任何和所有字段都必须标记为 final。

  2. 当您扩展 StatelessWidget 时,您创建了一个 Widget,因此 MyAppBar 现在是一个 Widget,就像 Column 或 Center 一样,因此所有关于 Widget 的规则都有效。它还需要一个标题,因为您在 MyAppBar 的构造函数中引用了一个标题变量。

希望这可以澄清您的任何问题!


推荐阅读