Here is my code
class FakturPage extends StatefulWidget {
const FakturPage({Key? key}) : super(key: key);
static String id = 'fakturpage';
@override
State<FakturPage> createState() => _FakturPageState();
}
class _FakturPageState extends State<FakturPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
DropdownTextfield(),
],
),
);
}
}
and this is the DropdownTextfield widget code, where I tried to make a UI that shows a Textfield and a DropdownButton that has options inputted from the Textfield above it.
class DropdownTextfield extends StatefulWidget {
@override
_DropdownTextfieldState createState() => _DropdownTextfieldState();
}
class _DropdownTextfieldState extends State<DropdownTextfield> {
var selectedOption;
TextEditingController textfieldValue = TextEditingController();
final List<String> options = [];
@override
void initState() {
super.initState();
selectedOption = (options.isNotEmpty ? options[0] : null)!;
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextField(
onChanged: (value) {
setState(() {
value = textfieldValue.text;
});
},
),
DropdownButton<String>(
value: selectedOption,
onChanged: (value) {
setState(() {
selectedOption = value!;
});
},
items: options.map((option) {
return DropdownMenuItem<String>(
value: option,
child: Text(option),
);
}).toList(),
),
TextButton(
onPressed: () {
setState(() {
options.add(textfieldValue.text);
});
},
child: Text("Add Option"),
),
],
);
}
}
I don’t know what went wrong. I tried to figure out if my custom dropdown widget is the problem but I can’t find anything wrong. I’ve been trying to fix this for almost an hour without finding the solution, since I’m new to the mobile development world. Can you help me?
>Solution :
The issue is you are using null-assert(!
) though you are doing null check.
Replace
selectedOption = (options.isNotEmpty ? options[0] : null)!;
With
selectedOption = options.isNotEmpty ? options[0] : null;