我不斷收到一個錯誤,標題,引數'title'不能有'null'的值,但隱含的默認值為null,backgorund和icon也是如此,
請我不確定,因為我是 Flutter 的新手,問題出在哪里,有人可以幫我檢查我的錯誤來自哪里。提前致謝。
這是我的 main.dart 檔案,
import 'package:simpleapp/models/sidebar.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
//stless - stateless widget..
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SidebarRow(item: sidebarItem[0]), //where i called the item
),
),
);
}
}
class SidebarRow extends StatelessWidget {
SidebarRow({required this.item});
final SidebarItem item;
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
width: 42.0,
height: 42.0,
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14.0),
gradient: item.background,
),
child: item.icon),
SizedBox(width: 12), // used for spacing..
Container(
child: Text(
item.title,
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.w800,
color: Color(0xff242629)),
),
),
],
);
}
}
sidebar.dart - 帶有附加示例資料的 SidebarItem 類檔案
import 'package:flutter/material.dart';
class SidebarItem {
//how can i initialize this class to accept null values..
SidebarItem({ this.title, this.background, this.icon });
String title;
LinearGradient background;
Icon icon;
}
//add sample data...
var sidebarItem = [
SidebarItem(
title: "Home",
background: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFF00AEFF),
Color(0xFF0076FF),
],
),
icon: Icon(Icons.home, color: Colors.white)
)];
請問我該如何解決這個錯誤并讓變數正確初始化,而不是設定為null。謝謝。
uj5u.com熱心網友回復:
這里有兩個例子:
如果每個實體變數都將被初始化(你的情況):
- 在您的命名引數中添加必需的關鍵字
class SidebarItem {
String title;
LinearGradient background;
Icon icon;
const SidebarItem({
required this.title,
required this.background,
required this.icon,
});
}
或者一個常數,如果它不會變異
class SidebarItem {
final String title;
final LinearGradient background;
final Icon icon;
SidebarItem({
required this.title,
required this.background,
required this.icon,
});
}
如果每個實體變數都可以為空
class SidebarItem {
String? title;
LinearGradient? background;
Icon? icon;
SidebarItem({
this.title,
this.background,
this.icon,
});
}
uj5u.com熱心網友回復:
添加?可選欄位。添加required強制引數
class SidebarItem {
SidebarItem({ this.title, required this.background, required this.icon });
String? title;
LinearGradient background;
Icon icon;
}
uj5u.com熱心網友回復:
請在此處查看有關設定可為空值的說明https://stackoverflow.com/a/68058488/13474354
在您的情況下,您required在建構式宣告中的引數之前缺少關鍵字
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/408819.html
標籤:
