i have the follwing ListView.builder
List fieldName = [
{
'name':Alex,
'values' [1,2,3,4],
},
{
'name':jack,
'values' ['jack','samer'],
}
]
ListView.builder(
itemCount: fieldName.length,
itemBuilder: (BuildContext context, int index) {
return DropdownButtonFormField(
onChanged: (theLang) {},
items: fieldName[index]['values']
.map<DropdownMenuItem<String>>(( String value){
return DropdownMenuItem(
value: value,
child: Text (value),
);
}).toList()
);
)
error message type '(String) => DropdownMenuItem' is not a subtype of type '(int) => DropdownMenuItem' of 'f'
i know this because the int
list .. but how could i make it work .. the list values comes from server .. sometimes int
sometimes strings
i tried to remove the type name in
.map((value){.... but still no hope
CodePudding user response:
Here you have indicated that the DropdownMenuItem
will handle value of type String
by including the type like this DropdownMenuItem<String>
Just use it without the datatype like this,
return DropdownButtonFormField(
items: ['A', 1].map(
(value) =>
DropdownMenuItem(
value: value,
child: Text('$value'),),).toList(),
onChanged: (x) {},
);
also dont forget to use String interpolation while using the value in Text()
widget
CodePudding user response:
The value field just call toString() like the code below.
import 'package:flutter/material.dart';
class Test extends StatelessWidget {
const Test({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
const fieldName = [
{
'name': "Alex",
'values': [1, 2, 3, 4],
},
{
'name': "jack",
'values': ['jack', 'samer'],
}
];
return SizedBox(
height: 200,
child: ListView.builder(
itemCount: fieldName.length,
itemBuilder: (BuildContext context, int index) {
return DropdownButtonFormField(
onChanged: (theLang) {},
items: (fieldName[index]['values'] as List)
.map<DropdownMenuItem<String>>((value) {
return DropdownMenuItem(
value: value.toString(),
child: Text(value.toString()),
);
}).toList());
}),
);
}
}