Md Zihad
Md Zihad

Reputation: 97

how to pass data between screen flutter?

I am new to flutter please help me.My scenario like that I have a list such as List test = ["one","two","three"] and two pages (homepage and details page). Home page contains listview.For specipic list view items has two textview one is list data according to index such as "one", another one want to keep initially empty string.when click specipic item it will navigate to details page.Details page contains a textview and button after clicked that button it will back to home page and rebuild the ui for specipic item and show done text instead of empty string.How can i achive that.Here is a sample code that i have tried

//homepage
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> test = ["one", "two", "three", "four"];
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(),
    body: Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: ListView.builder(
        itemCount: test.length,
        itemBuilder: (context, index) {
          return Item(testdata: test[index]);
        },
      ),
    ),
  );
}
}

//itempage

class Item extends StatefulWidget {
final String testdata;
const Item({super.key, required this.testdata});
@override
State<Item> createState() => _ItemState();
}
class _ItemState extends State<Item> {
@override
Widget build(BuildContext context) {
  return Padding(
    padding: const EdgeInsets.all(20.0),
    child: GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => Details(data: widget.testdata),
            ));
      },
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(widget.testdata),
            Text(""),
          ],
        ),
      ),
    ),
  );
}
}
//details page
class Details extends StatefulWidget {
final String data;
const Details({super.key, required this.data});

@override
State<Details> createState() => _DetailsState();
}

class _DetailsState extends State<Details> {
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("This is Details Page"),
    ),
    body: Center(
      child: Column(
        children: [
          Text(widget.data),
          SizedBox(
            height: 30,
          ),
          ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text("Done"))
        ],
      ),
    ),
  );
}
}

Upvotes: -1

Views: 999

Answers (3)

codrikaz
codrikaz

Reputation: 293

I used Gatx because I also wanted an index.

Get.to(ProfileView(), arguments: {
                      'userData': _trendingController.userData[index],
                      'index': index,
                    });

Inside the class i've using the map and put it the model value in the map variable

late UserModel userData;
int index = 0;

and then get the value in initstate

void initState() {
super.initState();
if (Get.arguments != null) {
  final Map<String, dynamic> args = Get.arguments;
   userData = args['userData'];
  final index = args['index'];
  print("indeccc $index");
  print("indeccc UserDataa ${userData.userFirstName}");
}
}

Upvotes: 1

eamirho3ein
eamirho3ein

Reputation: 17950

Inside Item class change on tap to this:

onTap: () {
   bool? result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => Details(data: widget.testdata),
        ));
   if (result != null && result) {
     setState(() {
        _message = 'done';
     });
     
   }
},

and also define new variable like this:

class _ItemState extends State<Item> {

   String _message = '';

   @override
   Widget build(BuildContext context) {
     return Padding(
     ...
   }
}

then inside Details page pop like this:

onPressed: () {
    Navigator.pop(context, true);
},

Upvotes: 1

Randal Schwartz
Randal Schwartz

Reputation: 44186

Any data that isn't directly related to creating a view should not be in the State of a widget... it should be in global space, and usually managed by some sort of State Management (like RiverPod or BLoC).

Once you understand that your app state belongs outside the widgets, the discussion of "sending data from one page to another" become pointless.

Upvotes: 2

Related Questions