Error GlobalKey Flutter Detected, How solve? - flutter

after a few weeks of using Flutter CRUD I was running normally and able to enter the database, but this time I encountered an error as shown below.
The error appears when I finish editing data, delete data. What do you think the solution to this problem is, friends?
Here I provide a snippet of my source code
listnasabah.dart
class ListNasabah {
ApiService apiService;
ListNasabah({this.apiService});
void getNasabah() {
apiService.getNasabah().then((nasabah) {
print(nasabah);
});
}
Widget createViewList() {
return SafeArea(
child: FutureBuilder(
future: apiService.getNasabah(),
builder: (BuildContext context, AsyncSnapshot<List<Nasabah>> snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(
'Something wrong with message: ${snapshot.error.toString()}',
textAlign: TextAlign.center,
),
);
} else if (snapshot.connectionState == ConnectionState.done) {
List<Nasabah> nasabah = snapshot.data;
return nasabahListView(nasabah);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
Widget nasabahListView(List<Nasabah> listnasabah) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
Nasabah nasabah = listnasabah[index];
return Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
nasabah.nama_debitur,
style: Theme.of(context).textTheme.bodyText1,
),
Text(nasabah.alamat),
Text(nasabah.no_ktp),
Text(nasabah.no_telp),
Text(nasabah.no_selular),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ElevatedButton.icon(
onPressed: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Hapus Data Nasabah'),
content: Text(
'Apakah anda yakin ingin menghapus data nasabah ini?'),
actions: [
TextButton(
child: Text('Yes'),
onPressed: () async {
apiService
.deleteNasabah(nasabah.id)
.then((value) => Navigator.of(
context)
.pushReplacement(
MaterialPageRoute(
builder: (context) =>
DataNasabah())));
})
],
),
);
},
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
icon: Icon(Icons.delete),
label: Text('Hapus'),
),
SizedBox(
width: 5,
),
ElevatedButton.icon(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailNasabah(
nasabah: nasabah,
),
),
);
},
icon: Icon(Icons.navigate_next),
label: Text(
'Detail',
),
)
],
)
],
),
),
),
);
},
itemCount: listnasabah.length,
),
);
}
}

Related

Showing empty widget while FutureBuilder is loading data

I have the following FutureBuilder:
child: FutureBuilder(
future: fetchNotifications(widget.usuarioId),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<dynamic>? filteredList = snapshot.data as List;
return ListView.separated(
separatorBuilder: (BuildContext context, int index) =>
new Divider(
color: Colors.black26,
thickness: 0.5,
),
itemCount: filteredList.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, index) {
NotificationModelo notificacion = filteredList[index];
var textoNot = notificacion.texto;
print("texto ${notificacion.texto}");
if (notificacion.texto == "New files available for you" &&
_fr) {
textoNot = "Nouveaux fichiers disponibles pour vous";
}
if (_fr) {}
return GestureDetector(
onTap: () {},
child: Container(
height: 50,
width: MediaQuery.of(context).size.width,
color: Colors.white,
child: GestureDetector(
onTap: () {
if (notificacion.categoria == "Travel Document") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
BDTravelDocumentsNuevo()));
}
if (notificacion.categoria == "Itinerary") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BDItineraryNuevo()));
}
if (notificacion.categoria == "Experience") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
BDExperiencesNuevo()));
}
if (notificacion.categoria == "News and Promos") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PrivateAreaNuevoDos()));
}
},
child: Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0),
child: Card(
elevation: 0,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: new Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
SizedBox(
width: 10,
),
notificacion.categoria ==
"Travel Document"
? CircleAvatar(
radius: 20.0,
backgroundImage: AssetImage(
"assets/item2.png"),
backgroundColor:
Colors.transparent,
)
: notificacion.categoria ==
"Itinerary"
? CircleAvatar(
radius: 20.0,
backgroundImage: AssetImage(
"assets/item3.png"),
backgroundColor:
Colors.transparent,
)
: notificacion.categoria ==
"Experience"
? CircleAvatar(
radius: 20.0,
backgroundImage: AssetImage(
"assets/item4.png"),
backgroundColor:
Colors.transparent,
)
: CircleAvatar(
radius: 20.0,
backgroundImage: AssetImage(
"assets/logolc.png"),
backgroundColor:
Colors.transparent,
),
SizedBox(
width: 15,
),
Row(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
Container(
width: 199,
height: 40,
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
"${textoNot}",
textAlign: TextAlign.start,
maxLines: 1,
overflow:
TextOverflow.ellipsis,
style: TextStyle(
fontSize: 15,
fontWeight:
FontWeight.bold),
),
],
),
),
],
),
Spacer(),
GestureDetector(
onTap: () {},
child: notificacion.categoria ==
"Push"
? Container()
: IconButton(
onPressed: () {
if (notificacion
.categoria ==
"Travel Document") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
BDTravelDocumentsNuevo()));
}
if (notificacion
.categoria ==
"Itinerary") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
BDItineraryNuevo()));
}
if (notificacion
.categoria ==
"Experience") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
BDExperiencesNuevo()));
}
if (notificacion
.categoria ==
"News and Promos") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PrivateAreaNuevoDos()));
}
},
icon: Icon(
Icons.arrow_forward_ios,
)),
)
],
),
),
),
)),
),
),
),
);
},
);
}
return AnyNotification();
}),
It is working as it should, the only issue is that I need to show the list data just after loading the data is finished, and now during loading time it is showing the widget AnyNotification(), which I want to show only when there are any data to show.
My customer doesn´t want to show anything during loading time.
You can follow this structure.
return FutureBuilder(
future: future,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text("got error");
}
if (snapshot.hasData) {
List<dynamic>? filteredList = snapshot.data as List?;
if (filteredList == null || filteredList.isEmpty) {
return AnyNotification();
} else {
return ListView.separated(
itemBuilder: itemBuilder,
separatorBuilder: separatorBuilder,
itemCount: itemCount,
);
}
}
return Text("NA State");
},
);
Find more about FutureBuilder-class.
Try the following code:
FutureBuilder(
future: fetchNotifications(widget.usuarioId),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return const Text("Error");
}
if (snapshot.hasData) {
List<dynamic>? filteredList = snapshot.data as List;
return ListView.separated(
separatorBuilder: (BuildContext context, int index) => const Divider(color: Colors.black26,thickness: 0.5),
itemCount: filteredList.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, index) {
NotificationModelo notificacion = filteredList[index];
var textoNot = notificacion.texto;
print("texto ${notificacion.texto}");
if (notificacion.texto == "New files available for you" && _fr) {
textoNot = "Nouveaux fichiers disponibles pour vous";
}
if (_fr) {}
return GestureDetector(
onTap: () {},
child: Container(
height: 50,
width: MediaQuery.of(context).size.width,
color: Colors.white,
child: GestureDetector(
onTap: () {
if (notificacion.categoria == "Travel Document") {
Navigator.push(context, MaterialPageRoute(builder: (context) => BDTravelDocumentsNuevo()));
}
if (notificacion.categoria == "Itinerary") {
Navigator.push(context, MaterialPageRoute(builder: (context) => BDItineraryNuevo()));
}
if (notificacion.categoria == "Experience") {
Navigator.push(context, MaterialPageRoute(builder: (context) => BDExperiencesNuevo()));
}
if (notificacion.categoria == "News and Promos") {
Navigator.push(context, MaterialPageRoute(builder: (context) => PrivateAreaNuevoDos()));
}
},
child: Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0),
child: Card(
elevation: 0,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const SizedBox(width: 10),
notificacion.categoria == "Travel Document"
? const CircleAvatar(
radius: 20.0,
backgroundImage: AssetImage("assets/item2.png"),
backgroundColor: Colors.transparent,
)
: notificacion.categoria == "Itinerary"
? const CircleAvatar(
radius: 20.0,
backgroundImage: AssetImage("assets/item3.png"),
backgroundColor: Colors.transparent,
)
: notificacion.categoria == "Experience"
? const CircleAvatar(
radius: 20.0,
backgroundImage: AssetImage("assets/item4.png"),
backgroundColor: Colors.transparent,
)
: const CircleAvatar(
radius: 20.0,
backgroundImage: AssetImage("assets/logolc.png"),
backgroundColor: Colors.transparent,
),
const SizedBox(width: 15),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 199,
height: 40,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"$textoNot",
textAlign: TextAlign.start,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
),
],
),
),
],
),
const Spacer(),
GestureDetector(
onTap: () {},
child: notificacion.categoria == "Push"
? Container()
: IconButton(
onPressed: () {
if (notificacion.categoria == "Travel Document") {
Navigator.push(context, MaterialPageRoute(builder: (context) => BDTravelDocumentsNuevo()));
}
if (notificacion.categoria == "Itinerary") {
Navigator.push(context, MaterialPageRoute(builder: (context) => BDItineraryNuevo()));
}
if (notificacion.categoria == "Experience") {
Navigator.push(context, MaterialPageRoute(builder: (context) => BDExperiencesNuevo()));
}
if (notificacion.categoria == "News and Promos") {
Navigator.push(context, MaterialPageRoute(builder: (context) => PrivateAreaNuevoDos()));
}
},
icon: const Icon(
Icons.arrow_forward_ios,
),
),
),
],
),
),
),
),
),
),
),
),
);
},
);
}
return AnyNotification();
},
),

can't refresh listview after update and delete flutter

Hello I'm a new flutter user, here I'm trying to complete CRUD but when I finish adding, editing, and deleting the listview page it can't be refreshed immediately. When I re-open the new page can be refreshed. Do you think friends here can solve my problem? Thank you good friends can help me.
Here's my source code snippet
Here is my source code snippet :
listnasabah.dart
class ListNasabah {
ApiService apiService;
ListNasabah({this.apiService});
void getNasabah() {
apiService.getNasabah().then((nasabah) {
print(nasabah);
});
}
Widget createViewList() {
return SafeArea(
child: FutureBuilder(
future: apiService.getNasabah(),
builder: (BuildContext context, AsyncSnapshot<List<Nasabah>> snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(
'Something wrong with message: ${snapshot.error.toString()}',
textAlign: TextAlign.center,
),
);
} else if (snapshot.connectionState == ConnectionState.done) {
List<Nasabah> nasabah = snapshot.data;
return nasabahListView(nasabah);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
Widget nasabahListView(List<Nasabah> listnasabah) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
Nasabah nasabah = listnasabah[index];
return Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
nasabah.nama_debitur,
style: Theme.of(context).textTheme.bodyText1,
),
Text(nasabah.alamat),
Text(nasabah.no_ktp),
Text(nasabah.no_telp),
Text(nasabah.no_selular),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FlatButton(
onPressed: () {
apiService
.deleteNasabah(nasabah.id)
.whenComplete(() {
Alert(
context: context,
type: AlertType.success,
title: "Sukses",
desc: "Data berhasil dihapus",
buttons: [
DialogButton(
child: Text(
"OK",
style: TextStyle(
color: Colors.white, fontSize: 20),
),
onPressed: () {
Navigator.pop(context);
},
width: 120,
)
],
).show();
});
},
child: Text(
"Hapus",
style: TextStyle(color: Colors.red),
),
),
TextButton(
onPressed: () async {
var result = await Navigator.push(context,
MaterialPageRoute(builder: (context) {
return FormAddNasabah(nasabah: nasabah);
}));
},
child: Text(
'Edit',
style: TextStyle(color: Colors.blue),
),
),
],
)
],
),
),
),
);
},
itemCount: listnasabah.length,
),
);
}
}
datanasabah.dart
class DataNasabah extends StatefulWidget {
DataNasabah({Key key}) : super(key: key);
final String title = "Data Nasabah";
#override
_DataNasabahState createState() => _DataNasabahState();
}
class _DataNasabahState extends State<DataNasabah> {
ApiService apiService;
ListNasabah _listNasabah;
#override
void initState() {
super.initState();
apiService = ApiService();
_listNasabah = new ListNasabah(apiService: apiService);
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldState,
appBar: AppBar(
title: Text(
'Data Nasabah',
style: TextStyle(color: Colors.white),
),
actions: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FormAddNasabah(),
),
);
},
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Icon(
Icons.add,
color: Colors.white,
),
),
)
],
),
body: _listNasabah.createViewList(),
);
}
}
If it's getting refreshed after you come back from another page then its problem with rendering UI as you are not using any state management here. You can check state management in flutter, I would suggest to use Provider(https://pub.dev/packages/provider).
For stateful widget you can use setState function.

How to deal with setState properly

void showSimpleCustomDialog(BuildContext context, String listName) async{
if(randList.isEmpty){
randList = await theDb.queryWhere("$listName");
}else{
randList.clear();
randList = await theDb.queryWhere("$listName");
}
setState((){
});
String randValue = "Click generate new to get a random value";
Dialog simpleDialog = Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
child: Text(
"$randValue"
),
),
Padding(
child: Row(
children: <Widget>[
RaisedButton(
color: Colors.blue,
onPressed: ()
String lol = randList[0 + rng.nextInt(randList.length - 0)].getItem();
print(randValue);
setState(() {
randValue = lol;
});
},
child: Text(
'generate new',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
)
],
),
),
],
),
),
);
showDialog(
context: context, builder: (BuildContext context) => simpleDialog);}
When I am clicking on "generate new" button I want to update my randomValue and to display that randomValue as Text Widget. To do that dynamically Im using setState, but it is not working, and i dont understand why. Please help me.
You should use StatefulBuilder with dialogue.
showDialog(
context: context,
builder: (context) {
String contentText = "Content of Dialog";
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Text("Title of Dialog"),
content: Text(contentText),
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text("Cancel"),
),
FlatButton(
onPressed: () {
setState(() {
contentText = "Changed Content of Dialog";
});
},
child: Text("Change"),
),
],
);
},
);
},

check firestore has document or not using Future Builder

Full code
class yourBookings extends StatefulWidget {
#override
_yourBookingsState createState() => _yourBookingsState();
}
class _yourBookingsState extends State<yourBookings> {
StateModel appState;
bool _loadingVisible = false;
#override
Widget build(BuildContext context) {
appState = StateWidget.of(context).state;
final number = appState?.user?.number ?? '';
Future getPosts() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore
.collection("confirmed_c_rides2")
.document(number)
.collection("1")
.getDocuments();
return qn.documents;
}
return Scaffold(
appBar: AppBar(
title: Text("Your Bookings :"),
),
body: Container(
child: FutureBuilder(
future: getPosts(),
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text("Loading ..."),
);
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
Widget image_carousel = new Container(
height: 200.0,
child: new Carousel(
//borderRadius: BorderRadius.all(Radius.circular(2.0)),
boxFit: BoxFit.fitHeight,
images: [
Image.network(
"${snapshot.data[index].data["driverImage"]}"),
Image.network(
"${snapshot.data[index].data["carImage"]}")
],
autoplay: true,
animationCurve: Curves.fastOutSlowIn,
animationDuration: Duration(milliseconds: 1000),
dotSize: 4.0,
indicatorBgPadding: 6.0,
dotBgColor: Colors.transparent,
),
);
return Card(
child: ListTile(
title: Column(
children: <Widget>[
SizedBox(height: 10),
Text(
"Status: ${snapshot.data[index].data["status"]}",
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
image_carousel,
Text(
"Name: ${snapshot.data[index].data["driverName"]}"),
SizedBox(height: 10),
Text(
"Gender: ${snapshot.data[index].data["gender"]}"),
SizedBox(height: 10),
Text(
"Experience: ${snapshot.data[index].data["experience"]}"),
SizedBox(height: 10),
Text(
"Number: ${snapshot.data[index].data["driverNumber"]}"),
SizedBox(height: 10),
Text(
"Time: ${snapshot.data[index].data["time"]}"),
SizedBox(height: 10),
Text(
"Scheduled on: ${snapshot.data[index].data["rideOn"]}"),
SizedBox(height: 10),
RaisedButton(
color: Colors.black,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => new issue()));
},
child: Text(
"Having issue",
style: TextStyle(color: Colors.white),
),
),
SizedBox(height: 10),
RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => rating1()));
},
child: Text("Rate driver"),
)
],
),
),
);
});
} else if (snapshot==null) {
return Center(
child: Text("not found..."),
);
}
return Center(
child: Text("not found 2..."),
);
}),
),
);
}
}
getPosts() refers to the firestore location for fetching data.
I want to check whether firestore contains number or not as a document using Future Builder.How can i do that?
number -> 1 contains further details.
If number does not exists then show data from firestore else show "not found...".How can i do that?
Future builder is used to stream firestore.

alertDialog didn't get called onPressed

Hi so I'm trying to show alertDialog when you press the close icon on the card but if I tap the "Close" button, it didn't show the alertDialog for delete confirmation, on the other hand when I tap the "check" Icon on, it successfully show a snackbar.
here's my code for the page:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'Schedule.dart';
class HomeView extends StatefulWidget {
HomeViewState createState() => HomeViewState();
}
class HomeViewState extends State<HomeView> {
final List<Schedule> scheduleList = [
Schedule("Hotel 1", DateTime.now(), DateTime.now(), "Germany"),
Schedule("Hotel 2", DateTime.now(), DateTime.now(), "France")
];
final Icon actionIcon = Icon(Icons.plus_one);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Dashboard"),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: actionIcon,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => UnscheduledField()),
);
},
)
],
),
body: Container(
child: ListView.builder(
itemCount: scheduleList.length,
itemBuilder: (context, int index) => buildCard(context, index)),
));
}
}
Widget buildCard(BuildContext context, int index) {
final List<Schedule> scheduleList = [
Schedule("Hotel 1", DateTime.now(), DateTime.now(), "Germany"),
Schedule("Hotel 2", DateTime.now(), DateTime.now(), "France")
];
final schedule = scheduleList[index];
return Container(
child: GestureDetector(
onTap: () {
showBottomSheet(
context: context,
builder: (context) => Container(
height: 550,
color: Colors.lightBlue,
));
},
child: Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 8, bottom: 4),
child: Row(
children: <Widget>[
Text(schedule.companyName,
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
Spacer(),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 4, bottom: 4),
child: Row(
children: <Widget>[Text(schedule.location)],
),
),
Padding(
padding: const EdgeInsets.only(top: 4.0, bottom: 4),
child: Row(
children: <Widget>[
Text('check in at:'),
Text(
"${DateFormat('HH:mm').format(schedule.startTime).toString()}"),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 4.0, bottom: 4),
child: Row(children: <Widget>[
Text('check out at:'),
Text(
"${DateFormat('HH:mm').format(schedule.endTime).toString()}"),
]),
),
Row(
children: <Widget>[
Expanded(
child: SizedBox(
height: 40,
child: ListTile(
trailing: IconButton(
onPressed: () {
alert(context);
},
icon: Icon(
Icons.close,
),
color: Colors.red,
),
),
),
),
Expanded(
child: SizedBox(
height: 40,
child: ListTile(
trailing: IconButton(
onPressed: () {
final snackbar = SnackBar(
content: Text('Successfully added'),
duration: Duration(seconds: 2),
);
Scaffold.of(context).showSnackBar(snackbar);
},
icon: Icon(
Icons.check,
),
color: Colors.lightGreen[300],
),
),
),
),
],
),
]))),
));
}
void alert(BuildContext context) {
var alertDialog = AlertDialog(
title: Text("Confirmation"),
content: Text("Are you sure you want to delete this?"),
actions: <Widget>[
FlatButton(
child: Text("No"),
onPressed: () {
Navigator.of(context).pop();
}),
FlatButton(
child: Text("Yes"),
onPressed: () {
Navigator.of(context).pop();
})
],
);
showDialog(
context: context,
builder: (BuildContext context) {
return alertDialog;
});
}
Any help would be appreciated! thanks
your code is perfect but you have to define alert dialog before you call it,
So define Alert Dialog before you call it in OnPress method of button and Pass it to alert method
class HomeView extends StatefulWidget {
HomeViewState createState() => HomeViewState();
}
class HomeViewState extends State<HomeView> {
final List<Schedule> scheduleList = [
Schedule("Hotel 1", DateTime.now(), DateTime.now(), "Germany"),
Schedule("Hotel 2", DateTime.now(), DateTime.now(), "France")
];
final Icon actionIcon = Icon(Icons.plus_one);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Dashboard"),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: actionIcon,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => UnscheduledField()),
);
},
)
],
),
body: buildCard(context, 0),
body: Container(
child: ListView.builder(
itemCount: scheduleList.length,
itemBuilder: (context, int index) => buildCard(context, index)),
)
);
}
}
Widget buildCard(BuildContext context, int index) {
final List<Schedule> scheduleList = [
Schedule("Hotel 1", DateTime.now(), DateTime.now(), "Germany"),
Schedule("Hotel 2", DateTime.now(), DateTime.now(), "France")
];
final schedule = scheduleList[index];
return Container(
child: GestureDetector(
onTap: () {
showBottomSheet(
context: context,
builder: (context) => Container(
height: 550,
color: Colors.lightBlue,
));
},
child: Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 8, bottom: 4),
child: Row(
children: <Widget>[
Text(schedule.companyName,
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
Spacer(),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 4, bottom: 4),
child: Row(
children: <Widget>[Text(schedule.location)],
),
),
Padding(
padding: const EdgeInsets.only(top: 4.0, bottom: 4),
child: Row(
children: <Widget>[
Text('check in at:'),
Text(
"${DateFormat('HH:mm').format(schedule.startTime).toString()}"),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 4.0, bottom: 4),
child: Row(children: <Widget>[
Text('check out at:'),
Text(
"${DateFormat('HH:mm').format(schedule.endTime).toString()}"),
]),
),
Row(
children: <Widget>[
Expanded(
child: SizedBox(
height: 40,
child: ListTile(
trailing: IconButton(
onPressed: () {
var alertDialog = AlertDialog(
title: Text("Confirmation"),
content:
Text("Are you sure you want to delete this?"),
actions: <Widget>[
FlatButton(
child: Text("No"),
onPressed: () {
Navigator.of(context).pop();
}),
FlatButton(
child: Text("Yes"),
onPressed: () {
Navigator.of(context).pop();
})
],
);
alert(context, alertDialog);
},
icon: Icon(
Icons.close,
),
color: Colors.red,
),
title: Text("hello"),
),
),
),
Expanded(
child: SizedBox(
height: 40,
child: ListTile(
trailing: IconButton(
onPressed: () {
final snackbar = SnackBar(
content: Text('Successfully added'),
duration: Duration(seconds: 2),
);
Scaffold.of(context).showSnackBar(snackbar);
},
icon: Icon(
Icons.check,
),
color: Colors.lightGreen[300],
),
),
),
),
],
),
]))),
));
}
void alert(BuildContext context, AlertDialog alertDialog) {
showDialog(
context: context,
builder: (BuildContext context) {
return alertDialog;
});
}