我是Flutter的新手。 我正在从flutter文档尝试此示例 https://api.flutter.dev/flutter/material/DropdownButton-class.html
Flutter Dropdown(包装在ListView小部件中)通过说``初始化器中只能访问静态成员''而给setState错误,任何人都可以帮我这个忙。提前致谢。
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
class PurchaseOrder extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: PO(),
);
}
}
class PO extends StatefulWidget {
@override
_POState createState() => new _POState();
}
class _POState extends State<PO> {
static String dropdownValue = 'One';
var purchasehandle = <Widget>[
Container(
padding: EdgeInsets.all(5.0),
child: Card(
child: Container(
padding: EdgeInsets.all(10.0),
child: Form(
child: ListView(
children: <Widget>[
Text(
"Purchase No 1",
style: TextStyle(fontWeight: FontWeight.bold)
),
DateTimePickerFormField(
inputType: InputType.date,
format: DateFormat("dd-MM-yyyy"),
editable: false,
decoration: InputDecoration(
hintText: 'Purchase Date',
hasFloatingPlaceholder: false
),
),
DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
setState(() { // Error Only static members can be accessed in initializers
dropdownValue = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
)
],
),
),
),
),
)
];
@override
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(
title: Text("VIX - Purchase Order"),
backgroundColor: const Color(0xFF2C3E50)
),
body: Stack(
children: purchasehandle,
),
);
}
}
答案 0 :(得分:0)
您已将dropdownValue
声明为静态变量,因此应从声明中删除static或将其用作_POState.dropdownValue
。
您可以详细了解here
答案 1 :(得分:0)
您只需要将小部件purchasehandle
的主体添加到小部件树本身,即在Stack
下的body
中。您无需将其声明为var。