dart - flutter/dart 中的 widget.something 到底调用了什么?

标签 dart flutter

我见过人们通过以下方式访问某些变量:widget.somethingwidget. 实际上在做什么?它引用了什么。

例如(我正在处理的一些随机代码):

import 'package:flutter/material.dart';
import 'Constants.dart';
import 'Lesson.dart';
import 'StaticMethods.dart';
import 'DetailPage.dart';
import 'package:garuda_academy_app/Authentication.dart';

class LessonPage extends StatefulWidget {
  LessonPage({Key key, this.auth, this.userId, this.onSignedOut, this.title}) : super(key: key);

  final String title;

  final BaseAuth auth;
  final VoidCallback onSignedOut;
  final String userId;

  @override
  _LessonPageState createState() => _LessonPageState();
}

class _LessonPageState extends State<LessonPage> {
  List lessons;

  @override
  void initState() {
    lessons = StaticMethods.getLessons();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ListTile makeListTile(Lesson lesson) => ListTile(
          contentPadding:
              EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
          leading: Container(
            padding: EdgeInsets.only(right: 12.0),
            decoration: new BoxDecoration(
                border: new Border(
                    right: new BorderSide(width: 1.0, color: Colors.white24))),
            child: IconButton(
              icon: Icon(Icons.file_download, color: Colors.white),
              onPressed: (){},
            ),
          ),
          title: Text(
            lesson.title,
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),

          subtitle: Row(
            children: <Widget>[
              Expanded(
                  flex: 1,
                  child: Container(
                    child: LinearProgressIndicator(
                        backgroundColor: Color.fromRGBO(209, 224, 224, 0.2),
                        value: lesson.indicatorValue,
                        valueColor: AlwaysStoppedAnimation(Colors.green)),
                  )),
              Expanded(
                flex: 4,
                child: Padding(
                    padding: EdgeInsets.only(left: 10.0),
                    child: Text(lesson.level,
                        style: TextStyle(color: Colors.white))),
              )
            ],
          ),
          trailing:
              Icon(Icons.keyboard_arrow_right, color: Colors.white, size: 30.0),
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => DetailPage(lesson: lesson)));
          },
        );

    Card makeCard(Lesson lesson) => Card(
          elevation: 8.0,
          margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
          child: Container(
            decoration: BoxDecoration(color: Color.fromRGBO(64, 75, 96, .9)),
            child: makeListTile(lesson),
          ),
        );

    final makeBody = Container(
      child: ListView.builder(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        itemCount: lessons.length,
        itemBuilder: (BuildContext context, int index) {
          return makeCard(lessons[index]);
        },
      ),
    );

    final makeBottom = Container(
      height: 55.0,
      child: BottomAppBar(
        color: Color.fromRGBO(58, 66, 86, 1.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            IconButton(
              icon: Icon(Icons.school, color: Colors.white),
              onPressed: () => StaticMethods.goToWidget(context, new LessonPage(title: LESSON_PAGE_TITLE, userId: widget.userId, ,)),
            ),
            IconButton(
              icon: Icon(Icons.flight_takeoff, color: Colors.white),
              onPressed: () {},
            ),
            IconButton(
              icon: Icon(Icons.account_box, color: Colors.white),
              onPressed: () {},
            )
          ],
        ),
      ),
    );
    final topAppBar = AppBar(
      elevation: 0.1,
      backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
      title: Text(widget.title),
      automaticallyImplyLeading: false,
    );

    return Scaffold(
      backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
      appBar: topAppBar,
      body: makeBody,
      bottomNavigationBar: makeBottom,
    );
  }
}

如果你注意到底部topAppBar一直使用widget.title。现在,这是从 LessonPage 访问标题,但我不明白。 widget.something 到底访问什么?

最佳答案

如果您看到代码 State<T extends StatefulWidget>在framework.dart文件中你会发现widget只是私有(private)类变量 _widget 的 getter .

framework.dart

abstract class State<T extends StatefulWidget> extends Diagnosticable {
  T get widget => _widget;
  T _widget;
}

抽象类State定义 widget属性 getter 如下 -

A State object's configuration is the corresponding StatefulWidget instance. This property is initialized by the framework before calling initState. If the parent updates this location in the tree to a new widget with the same runtimeType and Widget.key as the current configuration, the framework will update this property to refer to the new widget and then call didUpdateWidget, passing the old configuration as an argument.


简单来说,widget State的属性(property)类定义了当前StatefulWidget那你State指的是,因此它可用于访问 StatefulWidget 的运行时属性,正如您在示例中看到的,它可以是 title 中的值之一至userId .

希望这有帮助!

关于dart - flutter/dart 中的 widget.something 到底调用了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56286941/

相关文章:

Flutter in_app_purchase queryPastPurchases() 在 iOS 上返回空列表

file - Dart语言:编码(与HttpRequest和http_server包有关)

flutter - 如何绘制文字的形状?

flutter - Dio - QueuedInterceptor 处理具有多个请求的刷新 token

android - 如何将单选按钮放在文本旁边? - flutter

routes - 如何刷新路线页面

dart - Flutter后台悬浮窗功能

redux - Flutter 类型中间件

flutter - 如何在 Flutter for web TextField 上触发 onSubmitted

Android Studio Emulator Tool Windows 不显示