簡體   English   中英

Flutter 期望類型為“Widget”的值,但得到類型為“Null”的值

[英]Flutter Expected a value of type 'Widget', but got one of type 'Null'

我正在嘗試創建一個使用 Textinput 的 flutter 應用程序。 我將 TextInput 創建為名為“Textinput”的 class 和 function “renderTextInput”以具有更多兼容性我通過使用 class TextInputData 和 get s and set s。 代碼不會標記我的錯誤。

class Textinput {
  void renderTextInput(TextInputData textInputData) {
    Container(
      child: TextFormField(
        decoration: InputDecoration(labelText: textInputData.getText()),
        keyboardType: textInputData.getType(),
        style: textInputData.getStyle(),
      ),
      width: 400.0,
    );
  }
}
class TextInputData {
  String? _text;
  TextInputType? _type;
  TextStyle? _style;
  TextInputData(text, type, style) {
    _text = text;
    _style = style;
    _type = type;
  }
  String? getText() {
    return _text;
  }

  void setText(text) {
    _text = text;
  }

  TextInputType? getType() {
    return _type;
  }

  void setType(type) {
    _type = type;
  }

  TextStyle? getStyle() {
    return _style;
  }

  void setStyle(style) {
    _style = style;
  }
}

代碼中的用法

textInput.renderTextInput(TextInputData(
                "почта", TextInputType.emailAddress, _sizeTextBlack))

以及我如何在 main 中稱呼它

void main() {
  runApp(MaterialApp(title: 'Navigation Basics', home: AuthorizationScreen()));
}

如果您知道如何解決它,請告訴我。 我真的很感激。

根據您的代碼結構,我認為您需要返回小部件

class Textinput {
  Widget renderTextInput(TextInputData textInputData) {
    return Container(
      child: TextFormField(
        decoration: InputDecoration(labelText: textInputData.getText()),
        keyboardType: textInputData.getType(),
        style: textInputData.getStyle(),
      ),
      width: 400.0,
    );
  }
}

首先,請記住 void 意味着 Function 不返回任何內容。 有點,你需要在這里退貨。

其次,最好讓它成為無狀態小部件,而不是簡單的 class。只需創建一個無狀態小部件 class,並將參數提供給 function。然后在構建方法中返回小部件。 這是更標准和正確的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM