flutter – creating dropdown button with data from props

Issue

i’m learning flutter for some time and i have a problem that i dont know how to solve.
I’m trying to create a dropdown button with data that I pass from the parent,data is a list of words like [‘work’,’hobby’,’social’] etc.

My problem is the dropdown button after changing the value is still showing the initial one i think the problem is in the place when i initialize the "dropdownValue" because i do it in a build method but i cant acces properties from outside of that widget.

class TaskSheet extends StatefulWidget {
  @override
  _TaskSheetState createState() => _TaskSheetState();
  final List categories;
  TaskSheet(this.categories);
**// HERE I RECIVE THE LIST** 
}

class _TaskSheetState extends State<TaskSheet> {
  String dropdownValue;
  // I CANT ASSIGN VALUE HERE BECAUSE USING widget.categories  DONT WORK HERE AND IT MUST BE INSIDE BUILD METHOD
  @override
  Widget build(BuildContext context) {
    var categoriesList = widget.categories
        .map(
          (category) => DropdownMenuItem(
            value: category.title,
            child: Text(category.title),
          ),
        )
        .toList();
    dropdownValue = categoriesList[0].value; // THIS VALUE ALWAYS STAY THE SAME 

    return BottomSheet(
      builder: (context) => Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 16),
        child: Column(
          children: [
            Text('Add new task'),
            TextField(
              decoration: InputDecoration(labelText: 'What you wanna do?'),
            ),
            DropdownButton(
              icon: Icon(Icons.keyboard_arrow_down),
              focusColor: Theme.of(context).primaryColor,
              value: dropdownValue,
              onChanged: (newValue) {
                setState(() {
                  dropdownValue = newValue; // THIS HAVE NO IMPACT ON INITAL VALUE
                });
              },
              items: categoriesList,
            ),
          ],
        ),
      ),
      onClosing: () {},
    );
  }
}

I think if i find a way to acces widget.props from oustide of build method it going to work but I dont know how to do this

Solution

You can copy paste run full code below
You can see working demo below
Step 1: Category extends Equatable

import 'package:equatable/equatable.dart';

class Category extends Equatable {
  String title;
  Category({this.title});

  @override
  List<Object> get props => [title];
}

Step 2: dropdownValue is Category not String and use initState()

  Category dropdownValue;

  @override
  void initState() {
    dropdownValue = widget.categories[0];
    super.initState();
  }

Step 3: value is category

DropdownMenuItem<Category>(
            value: category,

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'package:equatable/equatable.dart';

class Category extends Equatable {
  String title;
  Category({this.title});

  @override
  List<Object> get props => [title];
}

class TaskSheet extends StatefulWidget {
  @override
  _TaskSheetState createState() => _TaskSheetState();
  final List<Category> categories;
  TaskSheet(this.categories);
}

class _TaskSheetState extends State<TaskSheet> {
  Category dropdownValue;

  @override
  void initState() {
    dropdownValue = widget.categories[0];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var categoriesList = widget.categories
        .map(
          (category) => DropdownMenuItem<Category>(
            value: category,
            child: Text(category.title),
          ),
        )
        .toList();

    return BottomSheet(
      builder: (context) => Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 16),
        child: Column(
          children: [
            Text('Add new task'),
            TextField(
              decoration: InputDecoration(labelText: 'What you wanna do?'),
            ),
            DropdownButton<Category>(
              icon: Icon(Icons.keyboard_arrow_down),
              focusColor: Theme.of(context).primaryColor,
              value: dropdownValue,
              onChanged: (newValue) {
                setState(() {
                  dropdownValue =
                      newValue; // THIS HAVE NO IMPACT ON INITAL VALUE
                });
                print(dropdownValue.title);
              },
              items: categoriesList,
            ),
          ],
        ),
      ),
      onClosing: () {},
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TaskSheet([
              Category(title: "work"),
              Category(title: "hobby"),
              Category(title: "social")
            ]),
          ],
        ),
      ),
    );
  }
}

Answered By – chunhunghan

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.