flutterflutter-layoutflutter-stateflutter-dialog

Flutter -Widget Text, not updating when value change even with SetState


I have created a container. His child is a text. When I tap on the container/text, it display a modal and a Picker. Then, the user can select a value. Press the confirm button and my text widget should change to display the value selected by the user. But in my case, it is not updating the value of the text widget. I have used that in the past and it was working very well. But here it is not and I do not see why. I am on this since 8:00. A little help would be appreciated. Many thanks.

int valuePickerUnitSelected =0;
String unitCount = '';
int unitCountInt;
String goal = "";

List <String> unitForHabits = ['Count', 'Minute(s)','Hour(s)','Gramme(s)', 'Pound(s)'];

class AddingHabitDetails extends StatefulWidget {
  const AddingHabitDetails({Key key}) : super(key: key);

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

class _AddingHabitDetailsState extends State<AddingHabitDetails> {
  BuildContext get ctx => null;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //drawer:  new MyMenu(), //TODO a remettre
      appBar: new AppBar(
        title: new Text('Habits'),
      ),
      body: Column(
        children: [
          titleZone('Name'),
          textFieldHabits('Habit name', context),
          titleZone('Goals'),
          FlatButton(

            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (unitCount.length < 2 )...[
                  Container(
                      width: 65,
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.blue,
                          ),
                          color: Colors.blue,
                          borderRadius: BorderRadius.all(Radius.circular(20))),

                      child:
                      Center(child: Text(
                          'Time', style: TextStyle(color: Colors.black,))))
                ]
                else
                  ...[
                    Container(
                        width: 65,
                        decoration: BoxDecoration(
                            border: Border.all(color: Colors.blue,),
                            color: Colors.blue,
                            borderRadius: BorderRadius.all(
                                Radius.circular(20))),
                        child: Center(
                            child: Text(
                            unitCount, style: TextStyle(color: Colors.black,))))
                  ],
              ],
            ),

            onPressed: () {
              setState(() {
                showModalBottomSheet(
                    context: context,
                    builder: (BuildContext context) {
                      return ShowPickerUnite(unitForHabits);
                    });
              },
              );
            },
          ),
          //ChipGoalV3(ctx),// ChipGoal(),
          textFieldHabits('Goals', context),
          titleZone('Frequency'),
          textFieldHabits('Frequency', context),
          titleZone('Time Range'),
          titleZone('Reminder'),
          titleZone('Habits Term'),
        ],
      ),
    );
  }

}
//########################################################################

class ShowPickerUnite extends StatefulWidget {
  List<String> myListUnit;
  ShowPickerUnite(this.myListUnit, {Key key}) : super(key: key);


  @override
  _ShowPickerUniteState createState() => _ShowPickerUniteState(
      myListUnit);
}

class _ShowPickerUniteState extends State<ShowPickerUnite> {
  List <String> myListUnit;

  _ShowPickerUniteState(this.myListUnit);

  @override
  Widget build(BuildContext context) {

    return Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            decoration: BoxDecoration(
              color: Color(0xffffffff),
              border: Border(
                bottom: BorderSide(
                  color: Color(0xffffffff),
                  width: 0.0,
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                  child: Text('Cancel'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16.0,
                    vertical: 5.0,
                  ),
                ),

                DefaultTextStyle(
                  style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.black,
                      fontWeight: FontWeight.bold),
                  child: Text('Select what you want'),
                ),

                // Text('Energy Needed', style: TextStyle(fontSize: 12.0, color: Colors.black),
                // ),

                CupertinoButton(
                  child: Text('Confirm'),
                  onPressed: () {
                    setState(() {

                      unitCount = unitForHabits[valuePickerUnitSelected];
                      print(unitCount);
                    });
                    Navigator.of(context).pop();
                  },
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16.0,
                    vertical: 5.0,
                  ),
                ),
              ],
            ),
          ),
          Container(
            //width: 360,
              height: 200,
              decoration:BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(15.0)),
              ),
              child: CupertinoPicker(
                  backgroundColor: Colors.white ,
                  useMagnifier: true,
                  magnification: 1.3,
                  scrollController: FixedExtentScrollController(initialItem: 0),
                  itemExtent: 25,

                  children: [

                    for (String name in myListUnit)
                      Center(
                          child:Text(name)),
                  ],
                  onSelectedItemChanged: (value) {
                    setState(() {
                      valuePickerUnitSelected = value;
                      // taskEnergy = myListEnergy[valuePickerEnergySelected];
                      // taskNewValue ['task_Energy'] = taskEnergy;
                    });
                  }))
        ]);
  }
}

Widget inputNameHabit (){
  return Padding(
    padding: const EdgeInsets.all(8.0),
    child: Text ('Name Habits',style: TextStyle(
        fontSize: 25,
        fontWeight: FontWeight.bold),),
  );
}

Widget titleZone (String _titleName){
  return Padding(
    padding: const EdgeInsets.all(8.0),
    child: Row(
      children: [
        Text ( _titleName,
          style: TextStyle(
              fontSize: 25,
              fontWeight: FontWeight.bold),),
      ],
    ),
  );
}

Widget textFieldHabits (String item,context){
  return TextField(
    decoration: InputDecoration(
      hintText: item,
      filled: true,
      fillColor: Colors.grey[300],
      border: OutlineInputBorder(
          borderSide: BorderSide.none,
          borderRadius: BorderRadius.circular(50)
      ),
    ),
  onTap: (){

    Navigator.push(context,
      MaterialPageRoute(
        builder: (context) => HabitGoalUnitSelection(), //TODO MODIFIER route selon source
      ),
    );
  },);
}

Solution

  • Wait for the dialog to finish and then call setState to update the UI.

    Modify this way

    onPressed: () async {
      await showModalBottomSheet(
          context: context,
          builder: (BuildContext context) {
            return ShowPickerUnite(unitForHabits);
          });
    
      setState(() {});