Home > Software design >  How to send a data from listview screen to form screen using flutter
How to send a data from listview screen to form screen using flutter

Time:09-14

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

CodePudding user response:

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()),
      ),
    );
  }
}

CodePudding user response:

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.

  • Related