-3

I am trying to send a data from ontap listview screen to form screen like image below. I have searched many references on google but I can't find any references that can help me, if you can provide solutions or references, I will greatly appreciate it. enter image description here

This is my sample code (ListPage Screen) :

 const ListPage({Key? key}) : super(key: key);
 @override
 State<ListPage> createState() => _ListPageState();
}

class _ListPageState extends State<ListPage> {
 TextEditingController textFieldController = TextEditingController();

 var _controller = TextEditingController();
 late bool searching, error;
 var data;
 late String query;
 String dataurl = "https://www.something.co.id/mobile/search_data.php";

 @override
 void initState() {
   searching = true;
   error = false;
   query = "";
   super.initState();
 }

 void getSuggestion() async {
   //get suggestion function
   var res = await http
       .post((Uri.parse(dataurl + "?query=" + Uri.encodeComponent(query))));
   //in query there might be unwant character so, we encode the query to url
   if (res.statusCode == 200) {
     setState(() {
       data = json.decode(res.body);
       //update data value and UI
     });
   } else {
     //there is error
     setState(() {
       error = true;
     });
   }
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       toolbarHeight: AppLayout.getHeight(100),
       automaticallyImplyLeading: false,
       title: searchField(),
       backgroundColor: Styles.background,
       elevation: 0.0,
     ),
     body: SingleChildScrollView(
       child: Container(
           alignment: Alignment.center,
           child: data == null
               ? Container(
                   padding: EdgeInsets.all(20),
                   child: searching
                       ? Text("Please wait")
                       : Text("Search any location")
                   //if is searching then show "Please wait"
                   //else show search peopels text
                   )
               : Container(
                   child: searching
                       ? showSearchSuggestions()
                       : Text("Find any location"),
                 )
           // if data is null or not retrived then
           // show message, else show suggestion
           ),
     ),
   );
 }

 Widget showSearchSuggestions() {
   List suggestionlist = List.from(data["data"].map((i) {
     return SearchSuggestion.fromJSON(i);
   }));
   //serilizing json data inside model list.
   return Column(
     children: suggestionlist.map((suggestion) {
       return InkResponse(
         // onTap: () {
         //   //when tapped on suggestion
         //   print(suggestion.id); //pint student id
         // },
         child: GestureDetector(
           onTap: () {
             _sendDataBack(context);
           },
           child: SizedBox(
             width: double.infinity, //make 100% width
             child: Card(
               child: Container(
                 decoration: BoxDecoration(color: Styles.background),
                 padding: EdgeInsets.all(15),
                 child: Text(
                   suggestion.name,
                   style: TextStyle(
                     fontSize: 20,
                     fontWeight: FontWeight.bold,
                   ),
                 ),
               ),
             ),
           ),
         ),
       );
     }).toList(),
   );
 }

 // get the text in the TextField and send it back to the FirstScreen
 void _sendDataBack(BuildContext context) {
   String textToSendBack = textFieldController.text;
   Navigator.pop(context, textToSendBack);
 }

 Widget searchField() {
   //search input field
   return Container(
     height: 50,
     child: TextField(
       controller: _controller,
       autofocus: true,
       style: Styles.textStyle,
       decoration: InputDecoration(
         hintStyle: TextStyle(color: Styles.colorDeepGrey),
         hintText: "Search Location...",
         prefixIcon: Icon(Icons.search),
         suffixIcon: _controller.text.length > 0
             ? IconButton(
                 onPressed: () {
                   _controller.clear();
                   setState(() {});
                 },
                 icon: Icon(Icons.cancel, color: Colors.grey))
             : null,
         enabledBorder: OutlineInputBorder(
           borderSide: BorderSide(
             color: Styles.colorLightBlack.withOpacity(0.20),
             width: 2,
           ),
           borderRadius: BorderRadius.circular(4),
         ), //under line border, set OutlineInputBorder() for all side border
         focusedBorder: OutlineInputBorder(
           borderSide: BorderSide(
             color: Styles.primaryColor,
             width: 1,
           ),
           borderRadius: BorderRadius.circular(4),
         ), // focused border color
       ), //decoration for search input field
       onChanged: (value) {
         query = value; //update the value of query
         getSuggestion(); //start to get suggestion
       },
     ),
   );
 }
}

//serarch suggestion data model to serialize JSON data
class SearchSuggestion {
 String id, name;
 SearchSuggestion({required this.id, required this.name});

 factory SearchSuggestion.fromJSON(Map<String, dynamic> json) {
   return SearchSuggestion(
     id: json["id"],
     name: json["name"],
   );
 }
}

Sample Code NextPage Screen :

class NextPage extends StatefulWidget {
  @override
  _NextPageState createState() => _NextPageState();
}

class _NextPageState extends State<NextPage> {
  int _currentStep = 0;
  StepperType stepperType = StepperType.vertical;
  String text = 'Text';
  var _controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text('Flutter Stepper Demo'),
        centerTitle: true,
      ),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child: Stepper(
                type: stepperType,
                physics: ScrollPhysics(),
                currentStep: _currentStep,
                onStepTapped: (step) => tapped(step),
                onStepContinue: continued,
                onStepCancel: cancel,
                steps: <Step>[
                  //Form Pengirim
                  Step(
                    title: new Text('Location'),
                    content: Column(
                      children: <Widget>[
                        SizedBox(
                          height: 50,
                          child: TextField(
                            onTap: () {
                              _awaitReturnValueFromSecondScreen(context);
                            },
                            controller: _controller,
                            autofocus: true,
                            onChanged: (text) {
                              setState(() {});
                            },
                            style: Styles.textStyle,
                            textInputAction: TextInputAction.next,
                            decoration: InputDecoration(
                              hintText: 'Location',
                              contentPadding:
                                  EdgeInsets.only(left: 15, right: 15),
                              hintStyle: TextStyle(color: Styles.colorDeepGrey),
                              suffixIcon: _controller.text.length > 0
                                  ? IconButton(
                                      onPressed: () {
                                        _controller.clear();
                                        setState(() {});
                                      },
                                      icon: Icon(Icons.cancel,
                                          color: Colors.grey))
                                  : null,
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color:
                                      Styles.colorLightBlack.withOpacity(0.20),
                                  width: 2,
                                ),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Styles.primaryColor,
                                  width: 1,
                                ),
                                borderRadius: BorderRadius.circular(4),
                              ),
                            ),
                          ),
                        ),
                    
                      ],
                    ),
                    isActive: _currentStep >= 0,
                    state: _currentStep >= 0
                        ? StepState.complete
                        : StepState.disabled,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _awaitReturnValueFromSecondScreen(BuildContext context) async {
    // start the SecondScreen and wait for it to finish with a result
    final result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => DataAlamat(),
        ));

    // after the SecondScreen result comes back update the Text widget with it
    setState(() {
      text = result;
    });
  }

  tapped(int step) {
    setState(() => _currentStep = step);
  }

  continued() {
    _currentStep < 2 ? setState(() => _currentStep += 1) : null;
  }

  cancel() {
    _currentStep > 0 ? setState(() => _currentStep -= 1) : null;
  }
}


  • 1
    https://stackoverflow.com/questions/53861302/passing-data-between-screens-in-flutter – mohammad esmaili Sep 14 '22 at 07:08
  • Does this answer your question? [Passing data between screens in Flutter](https://stackoverflow.com/questions/53861302/passing-data-between-screens-in-flutter) – jraufeisen Sep 14 '22 at 08:07

2 Answers2

0

Pass the tapped item value to the next page via named parameter of other page class.


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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: 10,
        itemBuilder: (context, index) {
          return ListTile(
            onTap: () {
              Navigator.push(context, MaterialPageRoute(
                builder: (context) {
                  return NextPage(value: index);
                },
              ));
            },
            title: Text(index.toString()),
          );
        },
      ),
    );
  }
}

class NextPage extends StatelessWidget {
  final int value;
  const NextPage({Key? key, required this.value}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(value.toString()),
      ),
    );
  }
}
0

Example in ListView screen, you have a variable called List<String> listLocations. Your ListView widget be like:

ListView.builder(
  itemCount: listLocations.length,
  itemBuilder: (context, index) {
    return InkWell(
      onTap: () => Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return SecondScreen(listLocations[index]);
        },
      )),
      child: ...
    );
  }
}

And your SecondScreen is a StatefulWidget (well it is a Form screen, so it would be Stateful, not Stateless, use TextEditingController in Form widget):

import 'package:flutter/material.dart';

class SecondScreen extends StatefulWidget {
  final String location;
  SecondScreen(this.location, {Key? key}) : super(key: key);

  @override
  State<SecondScreen> createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  var _textEditingController = TextEditingController();

  @override
  void initState() {
    _textEditingController.text = widget.location;
    super.initState();
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

You need to pass the location value in init state, and don't forget to dispose it.

Nguyen family
  • 749
  • 2
  • 12