【问题标题】:Trying to understand widget-object in flutter democode试图理解颤振演示代码中的小部件对象
【发布时间】:2019-05-09 23:32:45
【问题描述】:

我只是想学习flutter,flutter演示代码中有一段代码,你在创建一个新的flutter项目时得到的,我不明白:

标题:新文本(widget.title)

我不明白小部件的来源,因为它没有声明、定义或初始化。它指的是这个文本:

home: new MyHomePage(title: 'Flutter Demo Home Page')

但是为什么,它与上下文有关?如果它是预定义的,我可以如何以及在哪里使用它。 由于 Flutter 中的所有内容都是 Widget,因此很难向 Google 询问这个问题。

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
   });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
   );
  }
}    

【问题讨论】:

  • [Mod:我不能“评论”——没有足够的代表,但我认为这种赞赏确实值得公开表达。如果必须删除,也许您可​​以代表我将其发布在 cmets 中。] 感谢您提出这个问题和答案。我有同样的问题,并立即怀疑谷歌搜索,这个想法可能不受网络搜索的影响。然后我认为“小部件对象”有一个机会的幽灵(即使考虑到小部件对象这不太可能:)

标签: widget flutter


【解决方案1】:

MyHomePage 具有最终字段title,您在构造函数中声明它 - MyHomePage(title: 'Flutter Demo Home Page')``_MyHomePageState - 这是有状态小部件的状态。在每个州,您都可以使用 widget 来获取您的 StatefulWidget

【讨论】:

  • 感谢您的回答。小部件是否仅在引用其小部件的 State 对象中或在其他上下文中有意义?
  • 是的,仅在State 内,它指的是一个具体的小部件
猜你喜欢
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-30
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 2019-12-20
相关资源
最近更新 更多