Search code examples
flutterlistandroid-studiodartflutter-build

List without arguments causing error even called before the event


I am trying to feed one DropdownButton with a list of strings.

So my code start with :

List<String> list0 = [];

class mainPage extends StatefulWidget {
  const mainPage({super.key});

  @override
  State<mainPage> createState() => _mainPageState();
}
class _mainPageState extends State<mainPage> {
@override
  void initState() {
    list0.add("value1");
    list0.add("value 2");
    super.initState();
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Center(
         child: DropdownButton<String>(
              onChanged: (String? value) {
                 setState(() {
                 dropdownValue = value!;
              });
              items: list0.map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
        ),
      ),
    );
  }
}

What I am not understanding is the code are generating an error where say no values for list0. Cant be null.

So if I declarate like List list0 = ["0","1"]; no problens, will work fine. But I want to create an empty list to feed with my dynamic information...

What I am doing wrong guys?

Thank you!

I had tryed to clear the list. Create with one single element and remove it after but off course that is not correct.


Solution

  • It looks like you're referencing a dropdownValue variable without defining it first.

    Here's a dart file that I successfully compiled into a Flutter app:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) => const MaterialApp(home: MainPage());
    }
    
    class MainPage extends StatefulWidget {
      const MainPage({super.key});
    
      @override
      State<MainPage> createState() => _MainPageState();
    }
    
    class _MainPageState extends State<MainPage> {
      List<String> list0 = [];
      String dropdownValue = "";
      @override
      void initState() {
        list0.add("value1");
        list0.add("value2");
        dropdownValue = list0.first;
        super.initState();
      }
    
      DropdownMenuItem<String> item(String value) => DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
    
      @override
      Widget build(BuildContext context) => Scaffold(
            body: Center(
              child: DropdownButton<String>(
                value: dropdownValue,
                onChanged: (String? value) => setState(() => dropdownValue = value!),
                items: [for (final s in list0) item(s)],
              ),
            ),
          );
    }