Home > Back-end >  How to get values from one class screen to another class and populate those values in flutter?
How to get values from one class screen to another class and populate those values in flutter?

Time:10-24

I have one main class and TimePickerScreen class, I am trying to get the values from TimePickerScreen class to Main class to populate those values, I wraped From and To Text with GestureDetector to call TimePickerScreen class within bottomSheet and after selecting time and Tapping Save Button values should populate in place of select Time but I don't know how to get those values and below I pasted my code and screenshots, could anyone please help me, Thanks in Advance. screenshots of my work Main Class

import 'package:flutter/material.dart';
import 'package:single_selection_horizontal/timedatepicker_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "custom time picker horizontal",
      home: SelectTimeDate(),
    );
  }
}

class SelectTimeDate extends StatefulWidget {

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

class _SelectTimeDateState extends State<SelectTimeDate> {
  String pfromTime ='';
  String ptoTime ='';
  //String fromDate='';
  //String toDate='';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('custom time picker horizontal'),
      ),
      body: Center(
        child: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: pickerBottomSheet,
                child: Container(
                  child: Column(
                    children: [
                      Text(" From ",style: TextStyle(fontSize: 20,color: Colors.black),),
                      Text(
                        pfromTime==''
                        ? "Select Time"
                        : "$pfromTime",style: TextStyle(fontSize: 15,color: Colors.grey),),
                    ],
                  ),
                ),
              ),
              SizedBox(height: 10,),
              GestureDetector(
                onTap: pickerBottomSheet,
                child: Container(
                  child: Column(
                    children: [
                      Text(" To ",style: TextStyle(fontSize: 20,color: Colors.black),),
                      Text(
                        ptoTime==''
                        ? "Select Time"
                        : "$ptoTime",style: TextStyle(fontSize: 15,color: Colors.grey),),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  pickerBottomSheet(){
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        isDismissible: true,
        builder: (BuildContext context){
          return TimePickerScreen();
        }
        );
  }
}

TimePickerScreen

import 'package:flutter/material.dart';

class TimePickerScreen extends StatefulWidget {

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

class _TimePickerScreenState extends State<TimePickerScreen> {
  String selectedFromTime = " ";
  List<String> fromTimeList = ["0:00", "0:30", "1:00", "1:30", "2:00", "2:30", "3:00", "3:30", "4:00", "4:30", "5:00", "5:30", "6:00", "6:30"];
  List<bool> fromTimeListSelect =[false,false,false,false,false,false,false,false,false,false,false,false,false,false,];

  String selectedToTime =" ";
  List<String> toTimeList = ["0:00", "0:30", "1:00", "1:30", "2:00", "2:30", "3:00", "3:30", "4:00", "4:30", "5:00", "5:30", "6:00", "6:30"];
  List<bool> toTimeListSelect =[false,false,false,false,false,false,false,false,false,false,false,false,false,false,];

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.80,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        )
      ),
      child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            
            Container(
              padding: EdgeInsets.fromLTRB(50, 50, 50, 50),
                child: Text("Time Picker",style: TextStyle(fontSize: 40,color: Colors.purple),)),
            Divider(),
            Text("Select From Time",style: TextStyle(fontSize: 20,color: Colors.purple),),
            fromTime(),
            Divider(),
            Text("Select To Time",style: TextStyle(fontSize: 20,color: Colors.purple),),
            toTime(),
            FlatButton(onPressed: (){

            },
                color: Colors.purple,
                padding: EdgeInsets.fromLTRB(15, 15, 15, 15),
                child: Text("Save",style: TextStyle(fontSize: 20,color: Colors.white),)),
            SizedBox(height: 100,),
            Text('From : $selectedFromTime To : $selectedToTime'),

          ],
        ),
    );

  }
  Widget fromTime(){
    return Expanded(
      child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemCount: fromTimeList.length,
        itemBuilder: (BuildContext context,int index){
          return GestureDetector(
            child: Container(
              padding: EdgeInsets.all(6),
              child: Center(
                  child: Text(fromTimeList[index],
                    style: TextStyle(color: fromTimeListSelect[index] ? Colors.white : Colors.black ,fontSize: 16),)),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: fromTimeListSelect[index] ? Colors.purple : Colors.white,
              ),
            ),
            onTap: (){
              setState(() {
                for(int i=0; i< fromTimeListSelect.length; i  ){
                  fromTimeListSelect[i] = false;
                }
                fromTimeListSelect[index] = !fromTimeListSelect[index];
                fromTimeListSelect[index] == true ? selectedFromTime =fromTimeList[index] : selectedFromTime= ' ';
                print(fromTimeListSelect[index]);
                print(fromTimeList[index]);
              });
            },
          );

        },),
    );
  }

  Widget toTime(){
    return Expanded(
      child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemCount: fromTimeList.length,
        itemBuilder: (BuildContext context,int index){
          return GestureDetector(
            child: Container(
              padding: EdgeInsets.all(6),
              child: Center(
                  child: Text(toTimeList[index],
                    style: TextStyle(color: toTimeListSelect[index] ? Colors.white : Colors.black ,fontSize: 16),)),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: toTimeListSelect[index] ? Colors.purple : Colors.white,
              ),
            ),
            onTap: (){
              setState(() {
                for(int i=0; i< toTimeListSelect.length;i  ) {
                  toTimeListSelect[i] = false;
                }
                toTimeListSelect[index] = !toTimeListSelect[index];
                toTimeListSelect[index] == true ? selectedToTime =toTimeList[index] : selectedToTime= ' ';
                print(toTimeListSelect[index]);
                print(toTimeList[index]);
              });
            },
          );

        },),
    );
  }
}

CodePudding user response:

You can define a class to model your result from the bottom sheet :

class TimeSelectResult{
  final String pFromTime;
  final String pToTime;

  TimeSelectResult(this.pFromTime, this.pToTime);
}

then inside the code of the bottomsheet, when the user selects the 2 times from and to, you call Navigator.of(context).pop(timeSelectResult) where timeSelectResult is a variable of your _TimePickerScreen populated with the results chosen by the user.

so you call the bottom sheet like this now:

 pickerBottomSheet() async {
    final TimeSelectResult? result = await showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        isDismissible: true,
        builder: (BuildContext context) {
          return TimePickerScreen();
        });

    if (result != null) {
      setState(() {
        pfromTime = result.pFromTime;
        ptoTime = result.pToTime;
      });
    }
  }

CodePudding user response:

Add a callback method TimePickerScreen on class level like

 final Function callback;

and use it on Save button like

      onPressed: () {
                widget.callback(selectedFromTime, selectedToTime); //here
                Navigator.of(context).pop();
              },

And use TimePickerScreen like

  return TimePickerScreen(
            callback: (String from, String to) {
              print("From $from TO $to");
             setState(() {
                pfromTime = from;
                ptoTime = to;
              });
            },
          );

making nullable String will be better choice in this, becasue its depend on user.

Full code

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "custom time picker horizontal",
      home: SelectTimeDate(),
    );
  }
}

class SelectTimeDate extends StatefulWidget {
  @override
  _SelectTimeDateState createState() => _SelectTimeDateState();
}

class _SelectTimeDateState extends State<SelectTimeDate> {
  String pfromTime = '';
  String ptoTime = '';
  //String fromDate='';
  //String toDate='';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('custom time picker horizontal'),
      ),
      body: Center(
        child: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: pickerBottomSheet,
                child: Container(
                  child: Column(
                    children: [
                      Text(
                        " From ",
                        style: TextStyle(fontSize: 20, color: Colors.black),
                      ),
                      Text(
                        pfromTime == '' ? "Select Time" : pfromTime,
                        style: TextStyle(fontSize: 15, color: Colors.grey),
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              GestureDetector(
                onTap: pickerBottomSheet,
                child: Container(
                  child: Column(
                    children: [
                      Text(
                        " To ",
                        style: TextStyle(fontSize: 20, color: Colors.black),
                      ),
                      Text(
                        ptoTime == '' ? "Select Time" : ptoTime,
                        style: TextStyle(fontSize: 15, color: Colors.grey),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  pickerBottomSheet() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        isDismissible: true,
        builder: (BuildContext context) {
          return TimePickerScreen(
            callback: (String from, String to) {
              print("From $from TO $to");
            },
          );
        });
  }
}

class TimePickerScreen extends StatefulWidget {
  final Function callback;

  const TimePickerScreen({Key? key, required this.callback}) : super(key: key);

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

class _TimePickerScreenState extends State<TimePickerScreen> {
  String selectedFromTime = " ";
  List<String> fromTimeList = [
    "0:00",
    "0:30",
    "1:00",
    "1:30",
    "2:00",
    "2:30",
    "3:00",
    "3:30",
    "4:00",
    "4:30",
    "5:00",
    "5:30",
    "6:00",
    "6:30"
  ];
  List<bool> fromTimeListSelect = [
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
  ];

  String selectedToTime = " ";
  List<String> toTimeList = [
    "0:00",
    "0:30",
    "1:00",
    "1:30",
    "2:00",
    "2:30",
    "3:00",
    "3:30",
    "4:00",
    "4:30",
    "5:00",
    "5:30",
    "6:00",
    "6:30"
  ];
  List<bool> toTimeListSelect = [
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.80,
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.only(
        topLeft: Radius.circular(10),
        topRight: Radius.circular(10),
      )),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
              padding: EdgeInsets.fromLTRB(50, 50, 50, 50),
              child: Text(
                "Time Picker",
                style: TextStyle(fontSize: 40, color: Colors.purple),
              )),
          Divider(),
          Text(
            "Select From Time",
            style: TextStyle(fontSize: 20, color: Colors.purple),
          ),
          fromTime(),
          Divider(),
          Text(
            "Select To Time",
            style: TextStyle(fontSize: 20, color: Colors.purple),
          ),
          toTime(),
          FlatButton(
              onPressed: () {
                widget.callback(selectedFromTime, selectedToTime); //here
                Navigator.of(context).pop();
              },
              color: Colors.purple,
              padding: EdgeInsets.fromLTRB(15, 15, 15, 15),
              child: Text(
                "Save",
                style: TextStyle(fontSize: 20, color: Colors.white),
              )),
          SizedBox(
            height: 100,
          ),
          Text('From : $selectedFromTime To : $selectedToTime'),
        ],
      ),
    );
  }

  Widget fromTime() {
    return Expanded(
      child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemCount: fromTimeList.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            child: Container(
              padding: EdgeInsets.all(6),
              child: Center(
                  child: Text(
                fromTimeList[index],
                style: TextStyle(
                    color:
                        fromTimeListSelect[index] ? Colors.white : Colors.black,
                    fontSize: 16),
              )),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: fromTimeListSelect[index] ? Colors.purple : Colors.white,
              ),
            ),
            onTap: () {
              setState(() {
                for (int i = 0; i < fromTimeListSelect.length; i  ) {
                  fromTimeListSelect[i] = false;
                }
                fromTimeListSelect[index] = !fromTimeListSelect[index];
                fromTimeListSelect[index] == true
                    ? selectedFromTime = fromTimeList[index]
                    : selectedFromTime = ' ';
                print(fromTimeListSelect[index]);
                print(fromTimeList[index]);
              });
            },
          );
        },
      ),
    );
  }

  Widget toTime() {
    return Expanded(
      child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemCount: fromTimeList.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            child: Container(
              padding: EdgeInsets.all(6),
              child: Center(
                  child: Text(
                toTimeList[index],
                style: TextStyle(
                    color:
                        toTimeListSelect[index] ? Colors.white : Colors.black,
                    fontSize: 16),
              )),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: toTimeListSelect[index] ? Colors.purple : Colors.white,
              ),
            ),
            onTap: () {
              setState(() {
                for (int i = 0; i < toTimeListSelect.length; i  ) {
                  toTimeListSelect[i] = false;
                }
                toTimeListSelect[index] = !toTimeListSelect[index];
                toTimeListSelect[index] == true
                    ? selectedToTime = toTimeList[index]
                    : selectedToTime = ' ';
                print(toTimeListSelect[index]);
                print(toTimeList[index]);
              });
            },
          );
        },
      ),
    );
  }
}

  • Related