我正在一个需要很多下拉按钮的小项目上工作,所以我决定使它动态化,因此我为dropdownbutton创建了一个单独的类,但是在运行它时出现错误,我不知道错误在哪里,还有其他有效的方法吗?我在哪里犯错误
import "package:flutter/material.dart";
import "buttons.dart";
void main(){
runApp(My_app());
}
class My_app extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _My_app();
}
}
class _My_app extends State<My_app>{
var color_list = ["RED","GREEN","BLUE"];
var weight_list = ["300","400","800"];
var color = [Colors.red,Colors.green,Colors.blue];
var weight = [FontWeight.w300,FontWeight.w400,FontWeight.w800];
var color_var = 0;
var weight_var = 0;
var milo = "RED" ;
Widget build(BuildContext context){
return MaterialApp(
title:"Font Designer",
home:Material(
child:Center(
child:Container(
child:Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
padding: EdgeInsets.only(top:40),
child:Dropy(color_list,color,color_var)
)
]
)
],
)
)
)
)
);
}
}
// buttons.dart
import "package:flutter/material.dart";
class Dropy extends StatefulWidget{
var listy;
var power;
var varie;
Dropy(var k,var m,var n){
this.listy = k;
this.power = m;
this.varie = n;
}
State<StatefulWidget> createState(){
return _Dropy(this.listy,this.power,this.varie);
}
}
class _Dropy extends State<Dropy>{
var tex;
var liy;
var pow;
var va;
var male;
_Dropy(var o,var p,var z){
this.liy = o;
this.pow = p;
this.va = z;
}
Widget build(BuildContext context){
return DropdownButton<String>(
items:liy.map((String etx) {
return DropdownMenuItem<String>(
value: etx,
child: Text(etx)
);
}).toList(),
onChanged: (String milo){
setState(() {
this.va = this.liy.indexOf(male);
male = milo;
});
},
value: male,);
}
}
有两个包,您可以参考源代码或直接使用它您可以使用套件https://pub.dev/packages/find_dropdown它还支持搜索和验证
完整示例代码
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:find_dropdown/find_dropdown.dart';
import 'user_model.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("FindDropdown Example")),
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: <Widget>[
FindDropdown(
items: ["Brasil", "Itália", "Estados Unidos", "Canadá"],
label: "País",
onChanged: print,
selectedItem: "Brasil",
showSearchBox: false,
validate: (String item) {
if (item == null)
return "Required field";
else if (item == "Brasil")
return "Invalid item";
else
return null;
},
),
FindDropdown<UserModel>(
label: "Nome",
onFind: (String filter) => getData(filter),
searchBoxDecoration: InputDecoration(
hintText: "Search",
border: OutlineInputBorder(),
),
onChanged: (UserModel data) => print(data),
),
FindDropdown<UserModel>(
label: "Personagem",
onFind: (String filter) => getData(filter),
onChanged: (UserModel data) {
print(data);
},
dropdownBuilder: (BuildContext context, UserModel item) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).dividerColor),
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: (item?.avatar == null)
? ListTile(
leading: CircleAvatar(),
title: Text("No item selected"),
)
: ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(item.avatar),
),
title: Text(item.name),
subtitle: Text(item.createdAt.toString()),
),
);
},
dropdownItemBuilder:
(BuildContext context, UserModel item, bool isSelected) {
return Container(
decoration: !isSelected
? null
: BoxDecoration(
border:
Border.all(color: Theme.of(context).primaryColor),
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item.name),
subtitle: Text(item.createdAt.toString()),
leading: CircleAvatar(
backgroundImage: NetworkImage(item.avatar),
),
),
);
},
),
],
),
),
);
}
Future<List<UserModel>> getData(filter) async {
var response = await Dio().get(
"http://5d85ccfb1e61af001471bf60.mockapi.io/user",
queryParameters: {"filter": filter},
);
var models = UserModel.fromJsonList(response.data);
return models;
}
}
或使用包https://pub.dev/packages/dropdown_formfield
完整的使用示例代码
import 'package:flutter/material.dart';
import 'package:dropdown_formfield/dropdown_formfield.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _myActivity;
String _myActivityResult;
final formKey = new GlobalKey<FormState>();
@override
void initState() {
super.initState();
_myActivity = '';
_myActivityResult = '';
}
_saveForm() {
var form = formKey.currentState;
if (form.validate()) {
form.save();
setState(() {
_myActivityResult = _myActivity;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dropdown Formfield Example'),
),
body: Center(
child: Form(
key: formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.all(16),
child: DropDownFormField(
titleText: 'My workout',
hintText: 'Please choose one',
value: _myActivity,
onSaved: (value) {
setState(() {
_myActivity = value;
});
},
onChanged: (value) {
setState(() {
_myActivity = value;
});
},
dataSource: [
{
"display": "Running",
"value": "Running",
},
{
"display": "Climbing",
"value": "Climbing",
},
{
"display": "Walking",
"value": "Walking",
},
{
"display": "Swimming",
"value": "Swimming",
},
{
"display": "Soccer Practice",
"value": "Soccer Practice",
},
{
"display": "Baseball Practice",
"value": "Baseball Practice",
},
{
"display": "Football Practice",
"value": "Football Practice",
},
],
textField: 'display',
valueField: 'value',
),
),
Container(
padding: EdgeInsets.all(8),
child: RaisedButton(
child: Text('Save'),
onPressed: _saveForm,
),
),
Container(
padding: EdgeInsets.all(16),
child: Text(_myActivityResult),
)
],
),
),
),
);
}
}