How to make listview that navigate to another page when clicked

1,170

Solution 1

Please try this. This is Model Class

class Item{
  String title;
  String longText;
  String imageUrl;
  Item({this.title,this.longText,this.imageUrl});
}

this is First Screen

class FirstScreen extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<FirstScreen> {
  List<Item> _itemList = [
    Item(title: "title1", longText: "longtext1", imageUrl: "https://picsum.photos/200/300"),
    Item(title: "tite2", longText: "longtext2", imageUrl: "https://picsum.photos/200/300")
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Sharing data between screens'),
        ),
        body: Center(
            child: ListView.builder(
          itemCount: _itemList.length,
          itemBuilder: (context, index) {
            return GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => DetailScreen(item: _itemList[index])),
                  );
                },
                child: Container(margin: EdgeInsets.all(20), child: Text(_itemList[index].title)));
          },
        )));
  }
}

this is details screen

import 'package:flutter/material.dart';

import 'model/item.dart';

class DetailScreen extends StatelessWidget {
  final Item item;
  const DetailScreen({Key key,this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Detail Screen"),
      ),
      body: Center(
        child: Column(
          children:[
            Text(item.longText),
            Image.network(item.imageUrl,fit: BoxFit.fill,),
          ]
        ),
      ),
    );
  }
}

Solution 2

You are looking for a GestureDetector

Just you need to return GestureDetector Like this:

itemBuilder: (context, index) {
        return GestureDetector(
            onTap: () {
              //Navigate to detailed screen
              ...
            },
            ....
      },
Share:
1,170
Aida Qilah
Author by

Aida Qilah

Updated on January 01, 2023

Comments

  • Aida Qilah
    Aida Qilah over 1 year

    I want to make listview that when user clicks on the list item, it will navigate to other detailed page that has a title, a long text and an image. Each listview item has their own respective page (that has title,text and image). But I don't know how to link between the listview ui and the detailed screen. I've been searching for days but I fail to understand how to do (I am a beginner to learn flutter). Below is the implemented ui I have done.

    This is the ui of listview screen I have implemented.

    This is the ui of detailed screen I have implemented.