我有一个文件:orderdetails.dart,其中有一个类:
class OrderDetails {
final shipmentNumber = "26";
}
需要检索该货件编号var并显示在小部件中,如下所示:
class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
OrderDetails orderDetails;
_MainPageState({this.orderDetails});
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(20),
child: Icon(Icons.message),
),
SizedBox(
width: 20,
),
Padding(
padding: const EdgeInsets.all(20),
child: Icon(Icons.person),
),
SizedBox(
width: 20,
),
Padding(
padding: const EdgeInsets.all(20),
child: Icon(Icons.exit_to_app),
),
],
),
Container(
height: 90,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Card(
color: Color(0xFF1f2032),
elevation: 5,
child: Container(
decoration: BoxDecoration(
color: Color(0xFF1f2032),
borderRadius: BorderRadius.circular(10),
),
width: 160,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
color: Color(0xfffeaf0d),
child: Container(
width: 40,
height: 40,
child: Icon(
Icons.local_shipping,
color: Colors.white,
),
),
),
),
Padding(
padding: const EdgeInsets.all(13),
child: Text(
orderDetails.shipmentNumber,
style: TextStyle(
color: Colors.white,
fontSize: 35,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
],
),
)
],
);
}
}
但是在文本小部件中无法获取所请求的值
NotSuchMethodError:在Null接收器Null上调用了吸气剂“ shipmentNumber”。
如果我打电话给主人
final shipmentNumber = "26";
它可以工作,但是我需要从外部窗口小部件中调用此变量。
答案 0 :(得分:0)
orderDetails
永远不会设置为状态,因此始终为null。
您可以将class _MainPageState extends State<MainPage> {
OrderDetails orderDetails;
@override
void initState() {
super.initState();
// setState is not needed in initState
orderDetails = OrderDetails()
}
@override
Widget build(BuildContext context) {
// ...
}
}
设置为状态(1),也可以将其作为窗口小部件参数(2)传递。
class MainPage extends StatefulWidget {
final OrderDetails orderDetails;
const MainPage({Key key, this.orderDetails}) : super(key: key);
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
@override
Widget build(BuildContext context) {
return Text(
widget.orderDetails.shipmentNumber, // Using widget's data
style: TextStyle(
color: Colors.white, fontSize: 35, fontWeight: FontWeight.bold),
);
}
}
MainPage(orderDetails: OrderDetails())
但是仍然要记住将值传递给它:{{1}}