這個問題在這里已經有了答案: Dart 中的命名引數和位置引數有什么區別? (7 個回答) 10 小時前關閉。
我知道花括號用于在物件的構造程序中要求屬性名稱,但是當我在屬性名稱周圍使用它時,它使得該屬性對于物件的構造不是必需的。
例如:
在以下代碼的末尾,我創建了一個名為ReusableCard. 在 的建構式中ReusableCard,當我沒有在屬性周圍放置花括號時colour,我的 IDE 在使用的??代碼的主要部分顯示錯誤ReusableCard,因為我沒有向它傳遞任何值。但是當我把花括號放在周圍時colour(如下圖所示),所有的錯誤都消失了。由于某種原因,該colour屬性不再是必需的屬性。我知道之前添加“@required”colour將使此屬性成為必需,但我想知道為什么添加花括號會消除錯誤。
import 'package:flutter/material.dart';
class InputPage extends StatefulWidget {
@override
_InputPageState createState() => _InputPageState();
}
class _InputPageState extends State<InputPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BMI CALCULATOR'),
),
body: Column(
children: [
Expanded(
child: Row(
children: [
Expanded(
child: ReusableCard() //no error shown even though I have not passed any values.
Expanded(
child: ReusableCard(), //no error shown
),
],
),
),
Expanded(
child: Row(
children: [
Expanded(child: ReusableCard()), //no error shown
],
),
),
Expanded(
child: Row(
children: [
Expanded(
child: ReusableCard(), //no error shown
),
Expanded(
child: ReusableCard(), //no error shown
),
],
),
),
],
),
);
}
}
class ReusableCard extends StatelessWidget {
Color colour;
ReusableCard({this.colour});
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(15.0),
height: 200.0,
width: 170.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: colour,
),
);
}
}
uj5u.com熱心網友回復:
花括號不僅使它成為一個命名引數,它還使它成為一個可選引數
uj5u.com熱心網友回復:
ReusableCard({this.colour}): 帶花括號colour的是一個命名引數。
命名引數是可選的。
如果您不為colour(如 in ReusableCard())提供值,colour則默認為 null。您不必提供值,這就是您的 IDE 沒有顯示錯誤的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426593.html
下一篇:為什么有按鍵同步-沒有星號
