I am having this kind of issue when I click on article while the search bar loads articles on a News Flutter app that fetch articles from WordPress API. I share screen and code to understand my case.
Icon search Button actions Home screen that opens search bar
actions: <Widget>[
/// First search icon
FutureBuilder<List>(
future: categoryNews.getNewsArticles(),
builder: (context, snapshot) {
if (snapshot == null || !snapshot.hasData || snapshot.connectionState != ConnectionState.done) {
return const SizedBox();
// const Icon(
// Icons.search,
// color: Colors.white,
// );
}
return IconButton(
icon: const Icon(
Icons.search,
color: Colors.white,
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SearchBar(posts: snapshot.data!,),
),
);
},
);
}),
],
Search bar once open show up articles but when I click on a article nothing happens
class SearchBar extends StatefulWidget {
final List posts;
const SearchBar({
Key? key,
required this.posts,
}) : super(key: key);
@override
_SearchBarState createState() => _SearchBarState();
}
class _SearchBarState extends State<SearchBar> {
final List _searchedPost = [];
late List _searchedArticles = [];
//late final data;
@override
Widget build(BuildContext context) {
//var _searchedPost;
return Scaffold(
appBar: AppBar(
title: TextField(
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
hintText: "Cerca Articolo",
hintStyle:
TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
border: InputBorder.none,
),
onChanged: (val) {
setState(() {
_searchedArticles = widget.posts.where((element) {
return element["title"]["rendered"].contains(val);
}).toList();
});
},
),
),
body: _searchedArticles.isEmpty
? Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/images/search-illustration.png",
height: 230,
),
const SizedBox(
height: 20,
),
const Text(
'Nessun articolo trovato!',
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontFamily: "Raleway",
fontWeight: FontWeight.w600,
),
),
const SizedBox(
height: 20,
),
const Text(
'Inserisci meglio le lettere o parole chiave dell’articolo che stai cercando e riprova.',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16.0,
color: Colors.black54,
fontFamily: "Raleway",
fontWeight: FontWeight.w400,
),
),
const SizedBox(
height: 30,
),
// Back to home btn
MaterialButton(
height: 50,
elevation: 0,
color: Colors.blue[900],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
'Torna alla home',
style: TextStyle(
fontSize: 16.0,
color: Colors.white,
fontFamily: "Raleway",
fontWeight: FontWeight.w600),
),
],
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
),
);
},
),
],
),
),
)
: ListView.builder(
itemCount: _searchedArticles.length,
itemBuilder: (context, i) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Card(
margin: const EdgeInsets.all(10),
elevation: 5,
shadowColor: Colors.black26,
color: Colors.white,
child: InkWell(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
//data["_embedded"]["wp:featuredmedia"][0]["link"],),
_searchedArticles[i]["_embedded"]
["wp:featuredmedia"][0]["link"] ==
null
? const Text("Nessuna immagine caricata")
: Image.network(
_searchedArticles[i]["_embedded"]
["wp:featuredmedia"][0]["link"],
width: double.infinity,
height: 220,
fit: BoxFit.cover,
),
// Title article
Column(
children: [
Padding(
padding: const EdgeInsets.only(
left: 16, top: 16, bottom: 16),
child: Row(
children: [
Expanded(
child: Text(
_searchedArticles[i]["title"]
["rendered"] as String,
maxLines: 3,
overflow: TextOverflow.clip,
softWrap: true,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
fontFamily: "Raleway",
),
),
),
],
),
)
],
),
],
),
),
onTap: () {
if (_searchedPost[i] != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ArticlePage(
data: _searchedPost[i],
),
),
);
}
},
),
),
],
);
},
),
);
}
}
The error as you can see in the pictures is on onTap data: _searchedPost[i], How can I fix this issue?
CodePudding user response:
From Seeing Your Code The On Tap Method is Calling _searchedPost[i]
While The List Used in the ListView Builder is _searchedArticles
So The Error Is For Giving An Index To An Empty List
CodePudding user response:
The index you use here:
onTap: () {
if (_searchedPost[i] != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ArticlePage(
data: _searchedPost[i],
),
),
);
}
},
are not for _searchedPost
, because it indicates the number of item inside _searchedArticles
. So if you want to use it you should do this:
if (_searchedPost != null && _searchedPost.isNotEmpty && _searchedPost[i] != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ArticlePage(
data: _searchedPost[i],
),
),
);
}