【问题标题】:How to pass variables to a StatefulWidget: This class is marked as '@immutable'如何将变量传递给 StatefulWidget:此类被标记为“@immutable”
【发布时间】:2019-08-09 22:42:40
【问题描述】:

我正在调用一个返回一行的类(Titletext),当它在我的模拟器中工作时,编辑器给了我一个警告,所以我试图找出正确的方法来处理这个问题,因为编辑器正在显示一个警告。

我尝试使用无状态小部件,但它应该接受值因此无法正常工作,我也尝试过 google 和 here,虽然有大量关于“此类(或此类类继承自)被标记为“@immutable””它并不能真正帮助我理解为什么我正在做的事情是不正确的。当我添加 final 关键字时,我的构造函数会生气,因为我的变量应该是 final 的。

import 'package:flutter/material.dart';
import './header.dart';
import './title.dart';

class NotificationsScreen extends StatefulWidget {
  createState() {
    return NotificationsScreenState();
  }
}

class NotificationsScreenState extends State<NotificationsScreen> {
  String searchString = '';
  Widget header = new Header();
  Widget title = new TitleText(Icons.notifications, 'Notifications');

  //team logo centered
  //List of notifications
  Widget build(context) {
    return Container(
        margin: EdgeInsets.all(20.0),
        alignment: Alignment.center,
        child: Column(
          children: [
            header,
            Container(margin: EdgeInsets.only(top: 25.0)),
            title,
          ],
        ),
      );

  }
}
import 'package:flutter/material.dart';

class TitleText extends StatefulWidget {
  IconData icon = IconData(0);
  String title = '';

  TitleText(this.icon, this.title);

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

class _TitleState extends State<TitleText> {
  @override
  Widget build(context) {
    return Container(
      width: double.infinity,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(widget.icon, size: 30),
          Text(widget.title),
        ],
      ),
    );
  }
}

输出按预期工作,但警告我显然处理了这个错误,我正在寻找我应该将值传递给像这样返回小部件的类的方式。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    正如注释所说,Widget 子类的所有属性都必须是不可变的/最终的。

    因此,如果你想给你的属性一个默认值,你必须在构造函数中这样做。

    代替:

    class Foo {
      String bar = "default";
    
      Foo({this.bar});
    }
    

    做:

    class Foo {
      final String bar;
      Foo({this.bar = "default"});
    }
    

    或:

    class Foo {
      final String bar;
      Foo({String bar}): bar = bar ?? "default";
    }
    

    【讨论】:

    • 我不想设置默认值,我想给最终的变量传递一个值。我试图将值传递给这个小部件,所以当我将它们标记为最终时,它会说因为它们是最终的,我无法更改它们(这当然是有道理的,因为它们被标记为最终的)
    • @halldorr 这还不清楚。您的 sn-p 从未修改过您的小部件的属性。
    • 我刚刚得到它,所以我给了他们默认值,这是错误的。感谢您的帮助。
    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 2019-08-25
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多