Search code examples
flutterfirebaseflutter-futurebuilderstream-builder

change variable depend on dropdown selection in StreamBuilder, Flutter


I'm currently writting a following code which

  1. fetch data and assign it as initial data
  2. create dropdown inside of streambuilder
  3. when dropdown is changed, change variable Now I am aware that this won't work because running setState will rerun streambuilder which rechange value of category1 to userData["category1"]. What modification would I need to fix this? I would like to solve it in method that not getting value with initstate.
List<DropdownMenuItem<String>> categoryList = [
    const DropdownMenuItem<String>(child: Text("ビューティー"), value: "ビューティー"),
    const DropdownMenuItem<String>(child: Text("ファッション"), value: "ファッション"),
    const DropdownMenuItem<String>(child: Text("カフェ"), value: "カフェ"),],
String? category1;

StreamBuilder(
  stream:FirebaseFirestore.instance.collection('user').doc(user.email!).snapshots(),
  builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot){
    if (snapshot.hasData){SizedBox(
      Map userData = snapshot.data!.data() as Map<String, dynamic>;
      category1 = userData["category1"];
      width: 220,
      child: DropdownButtonFormField(
        dropdownColor: Colors.white,
        style: const TextStyle(color: Colors.black),
        decoration: const InputDecoration(
          border: InputBorder.none,
        ),
        value: category1,
        items: categoryList,
        onChanged: (String? value) {
          setState(value){
            category1 = value;
          }
        },
      )),}
      }
  )

Reason why I don't won't to solve it with initstate is because I have exact problem with following question. question the initstate won't fill a data before widget are made and value return null.

tried to solve it by using initstate but didn't work


Solution

  • You could possibly try to check if the value of category1 is null before allocating value to it. So that you make sure only the first time the value is assigned. Like:

    if(category1 != null){
      category1 = userData["category1"];
    }