when running the application I get the following error where the setState() function is: (https://i.sstatic.net/kYQFF.png)
Here is my code for the main file:
import 'package:flutter/material.dart';
import 'quotes.dart';
import 'quote_card.dart';
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: QuoteList(),
));
class QuoteList extends StatefulWidget {
const QuoteList({super.key});
@override
State<QuoteList> createState() => _QuoteListState();
}
class _QuoteListState extends State<QuoteList> {
List<Quote> quotes = [
Quote(text: 'Be yourself; everyone else is already taken',author: "John"),
Quote(text: 'I have nothing to declare except my genius', author: "Brian"),
Quote(text: 'The truth is rarely pure and never simple', author: "Elize")
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
appBar: AppBar(
backgroundColor: Colors.amber,
title: Text('Awesome Quotes'),
centerTitle: true,
),
body: Column(
children: quotes.map((e) => QuoteCard(
quote: e,
delete: () {
setState(() {
quotes.remove(e);
});
}
)).toList(),
)
);
}
}
The QuoteCard class is as follows:
import 'package:flutter/material.dart';
import 'quotes.dart';
class QuoteCard extends StatelessWidget {
final Quote quote;
final Function delete;
QuoteCard({required this.quote, required this.delete});
@override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
color: Colors.amberAccent,
child: Padding(
padding: EdgeInsets.all(15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Center(
child: Text(
quote.text, style: TextStyle(
color: Colors.white
),
),
),
Center(
child: Text(
'-${quote.author}', style: TextStyle(
color: Colors.white
),
),
),
TextButton.icon(
onPressed: delete(),
label: Text('Delete Quote'),
icon: Icon(Icons.delete),
),
],
),
),
);
}
}
I want that when I click the delete button, the delete method should be invoked...delete an item in the list and this should reflect in the application right after the delete button is clicked...thhe item should no longer be there.
I could not find answers that dealt with this issue. Most videos on YouTuber use an older version of flutter and this works there. I am using Flutter 3.10.4 and Dart 3.0.3
Please, in the QuoteCard widget, replace
TextButton.icon(
onPressed: delete(),
label: Text('Delete Quote'),
icon: Icon(Icons.delete),
),
with this:
TextButton.icon(
onPressed: () => delete(),
label: Text('Delete Quote'),
icon: Icon(Icons.delete),
),
In the first case you are calling the delete function while the widget is being built.
In the second case, you call the delete function only when the button is pressed.