flutter firestore update data method - android

I'm trying to update the card data I brought from firestore
when I use onTap in Inkwell I want to change data in this card.
this is my search service. I am using this for bring data from firestore
how can I make update function on this situation. thanks for help
class SearchService {
List<Future<QuerySnapshot>> searchByName() {
return [
Firestore.instance
.collection('dis')
.where('no')
.orderBy('date', descending: true )
.getDocuments(),
];
}
}
this is my Card code
Widget buildResultCard(BuildContext context , data) {
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
elevation: 5,
child: ExpansionCard(
title: Column(
children: [
Row(
children: [
Padding(
padding: EdgeInsets.fromLTRB(5, 0, 5, 1),
child: Text(data['isim'],
style: GoogleFonts.montserrat(color: Colors.blueGrey[700], fontSize: 20 , textStyle: TextStyle(fontWeight: FontWeight.w400)),
textAlign: TextAlign.center,
),
),
InkWell(
child: Icon(
Icons.update,
color: Colors.white54,
),
onTap: (){//I want to set update function here//
},
)
],
),
);
}
and this is my adddata function
Future<void> addData(carData) async {
if (isLoggedIn()) {
Firestore.instance.collection('dis').add(carData).catchError((e) {
print(e);
});
} else {
print('You need to be logged in');
}
}
a little bit long but this is my addmethod
crudMedthods crudObj = new crudMedthods();
Future<bool> addDialog(BuildContext context) async {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
final _width = MediaQuery.of(context).size.width;
return AlertDialog(
title: Text('Temsilci Verisi Ekleyin.', style: GoogleFonts.montserrat(color: Colors.black54,
fontSize: 22 , textStyle: TextStyle(fontWeight: FontWeight.w300)),
textAlign: TextAlign.center,),
content: SingleChildScrollView(
child: Container(
width: _width,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
children: [
TextField(
onTap: (){
showDatePicker(context: context,
initialDate: _dateTime == null ? DateTime.now() : _dateTime,
firstDate: DateTime(2000),
lastDate: DateTime(2030)).then((date) {
setState(() {
_dateTime = date;
});
});
},
decoration: InputDecoration(hintText: _dateTime == null ? 'Uygulama Sıralama
Takvimi Giriniz' : _dateTime.toString()),
onChanged: (value) {
this._dateTime = value as DateTime;
},
),
],
),
SizedBox(height: 5.0),
TextField(
decoration: InputDecoration(hintText: 'Temsilci'),
onChanged: (value) {
this.temsilci = value;
},
),
SizedBox(height: 5.0),
TextField(
decoration: InputDecoration(hintText: 'Sıra No'),
onChanged: (value) {
this.sirano = value;
},
),
SizedBox(height: 5.0),
TextField(
decoration: InputDecoration(hintText: 'Tarih'),
onChanged: (value) {
this.tarih = value;
},
),
SizedBox(height: 5.0),
TextField(
decoration: InputDecoration(hintText: 'Veri Kaynağı'),
onChanged: (value) {
this.verik = value;
},
),
],
),
),
),
actions: <Widget>[
FlatButton(
child: Text('Verileri Sisteme Ekleyin'),
textColor: Colors.blue,
onPressed: () {
Navigator.of(context).pop();
crudObj.addData({
'date': this._dateTime,
'no': this.no,
'temsilci': this.temsilci,
'sıra no': this.sirano,
'tarih': this.tarih,
'veri kaynağı': this.verik,
}).then((result) {
dialogTrigger(context);
}).catchError((e) {
print(e);
});
},
)
],
);
});
}

Related

why I got the error in DateTime _selectedDate;?

this is my code
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
State<NewTransaction> createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
DateTime _selectedDate;
void _submitData() {
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
print('...');
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
controller: _amountController,
// onChanged: (val) => amountInput = val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Expanded(
child: Text(
_selectedDate == null
? 'No Date Chosen!'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}',
),
),
TextButton(
child: Text(
'Choose Date',
style: TextStyle(
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold,
),
),
onPressed: _presentDatePicker,
)
],
),
),
ElevatedButton(
child: Text(
'Add Transaction',
style: TextStyle(
color: Colors.white,
),
),
onPressed: _submitData,
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith(
(states) {
return Colors.purple;
},
),
),
),
],
),
),
);
}
}
there's a redline on DateTime _selectedDate;
what should I do?
You're trying to make it null in the code so that you check over it with e _selectedDate == null.
well, you can tell Dart that it can be null from its declaration with a ?:
DateTime? _selectedDate; // add ?

Switch Button not toggle flutter

hope all are doing well
i use a Switch Button in popup Form when pressing the floating action Button but its not working or the UI not updated when i pressed the Switch Button
I used it in a StatefulWidget but its not toggle until i press hot reload,if there any Suggestion please
here where i use the Switch :
void _openAlbumsDialog() {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Add an Album'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _form,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
initialValue: _albumInitValues['name'],
decoration: InputDecoration(
helperText: 'Album Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
),
textInputAction: TextInputAction.next,
onSaved: ((newValue) {
_editedALbum = Album(
albumId: DateTime.now().toString(),
albumName: newValue!,
albumLinks: _editedALbum.albumLinks,
);
}),
validator: (value) {
if (value!.isEmpty) {
return 'Please insert a Value';
} else {
return null;
}
},
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Private'),
Consumer<Album>(
builder: (context, value, child) => Switch.adaptive(
mouseCursor: MouseCursor.uncontrolled,
value: _isPrivate,
onChanged: (value) {
final albumProvider =
Provider.of<Album>(context, listen: false);
albumProvider.togglePrivateAlbum();
setState(() {
_isPrivate = value;
});
},
),
),
actions: [
TextButton(
onPressed: () {
FocusScope.of(context).unfocus();
_isLoading
? const Center(
child: CircularProgressIndicator(),
)
: _saveAlbumFOrm();
},
child: const Text('Save'))
],
));
}
#override
Widget build(BuildContext context) {
return SpeedDial(
children: [
SpeedDialChild(
child: const Icon(Icons.folder),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
label: 'Add a new Album',
labelStyle: const TextStyle(fontSize: 12.0),
onTap: _openAlbumsDialog,
),
],
);
}
}
void togglePrivate in Album Provider:
void togglePrivateAlbum() {
isPrivate = !isPrivate;
}
It happens so because you have to recreate your own StatefulBuilder(), so wrap your showDialog() with a StatefulBuilder() wich will then have the targeted state
StatefulBuilder(
builder:(context, StateSetter innerSetter){
....
//use the setter now
innerSetter(() {
_isPrivate = value;
});
....
})

_Cast Error : Null check operator used on a null value [duplicate]

This question already has answers here:
Null check operator used on a null value
(12 answers)
Closed last year.
I am new to programming and don't know how to solve this issue.
I am using the java version of 8 and using Android Studio to make apps with Flutter.
I have been making a to-do list app, and a cast error happens when
I make a new list
I update a list
I delete a list
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter ToDo List',
debugShowCheckedModeBanner: false,
theme: ThemeData(
fontFamily: "NanumSquare",
primaryColor: Color(0xFF424874), //primary color
),
home: HomeScreen()
);
}
}
this is the main.dart
the error appears on the Home Screen.
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late Future<List<Note>> _noteList;
final DateFormat _dateFormatter = DateFormat("MMM dd, yyyy");
DatabaseHelper _databaseHelper = DatabaseHelper.instance;
void initState() {
super.initState();
_updateNoteList();
}
_updateNoteList() {
_noteList = DatabaseHelper.instance.getNoteList();
}
Widget _buildNote(Note note) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 25),
child: Column(
children: [
Container(
margin: EdgeInsets.all(5),
color: Color(0xFFDCD6F7),
child: ListTile(
title: Text(
note.title!,
style: TextStyle(
fontSize: 20,
color: Color(0xFF424874),
decoration: note.status == 0
? TextDecoration.none
: TextDecoration.lineThrough),
),
subtitle: Text(
"${_dateFormatter.format(note.date!)}-${note.priority}",
style: TextStyle(
fontSize: 15,
color: Color(0xFF424874),
decoration: note.status == 0
? TextDecoration.none
: TextDecoration.lineThrough),
),
trailing: Checkbox(
onChanged: (value) {
note.status = value! ? 1 : 0;
DatabaseHelper.instance.updateNote(note);
_updateNoteList();
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (_) => HomeScreen())
);
},
activeColor: Color(0xFFA6B1E1),
value: note.status == 1 ? true : false,
),
onTap: () => Navigator.push(
context,
CupertinoPageRoute(
builder: (_) => AddNoteScreen(
updateNoteList: _updateNoteList(),
note: note
)
),
),
),
),
Divider(
height: 5,
color: Color(0xFFA6B1E1),
thickness: 2,
)
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFF4EEFF),
floatingActionButton: FloatingActionButton(
backgroundColor: Color(0xFF424874),
onPressed: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (_) => AddNoteScreen(
updateNoteList: _updateNoteList(),
),
));
},
child: Icon(Icons.add),
),
body: FutureBuilder(
future: _noteList,
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
final int completedNoteCount = snapshot.data!.where((Note note) => note.status == 1).toList().length;
return ListView.builder(
padding: EdgeInsets.symmetric(vertical: 80),
itemCount: int.parse(snapshot.data!.length.toString()) + 1,
itemBuilder: (BuildContext context, int index) {
if (index == 0) {
return Padding(
padding:
EdgeInsets.symmetric(horizontal: 40, vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"My Notes",
style: TextStyle(
color: Color(0xFF424874),
fontSize: 40,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"$completedNoteCount of ${snapshot.data.length}",
style: TextStyle(
color: Color(0xFFA6B1E1),
fontSize: 20,
fontWeight: FontWeight.w600),
),
],
),
);
}
return _buildNote(snapshot.data![index-1]);
});
}));
}
}
The error message is as below.
======== Exception caught by gesture ===============================================================
The following _CastError was thrown while handling a gesture:
Null check operator used on a null value
When the exception was thrown, this was the stack:
#0 _AddNoteScreenState._delete (package:crud_sqlite_app/screens/add_note_screen.dart:80:26)
#1 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#2 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
#3 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:607:11)
#4 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#e7613
debugOwner: GestureDetector
state: ready
won arena
finalPosition: Offset(150.8, 655.2)
finalLocalPosition: Offset(110.8, 46.2)
button: 1
sent tap down
====================================================================================================
and this is the add_note_screen.dart
class AddNoteScreen extends StatefulWidget {
final Note? note;
final Function? updateNoteList;
AddNoteScreen({this.note, this.updateNoteList});
#override
_AddNoteScreenState createState() => _AddNoteScreenState();
}
class _AddNoteScreenState extends State<AddNoteScreen> {
final _formKey = GlobalKey<FormState>();
String _title = "";
String _priority = "Low";
String btnText = "Add Note";
String titleText = "Add Note";
DateTime _date = DateTime.now();
TextEditingController _dateController = TextEditingController();
final DateFormat _dateFormatter = DateFormat("MMM dd, yyyy");
final List<String> _priorities = ["Low", "Medium", "High"];
#override
void initState(){
super.initState();
if(widget.note != null) {
_title = widget.note!.title!;
_date = widget.note!.date!;
_priority = widget.note!.priority!;
setState(() {
btnText = "Update Note";
titleText = "Update Note";
});
}
else {
setState(() {
btnText = "Add Note";
titleText = "Add Note";
});
}
_dateController.text = _dateFormatter.format(_date);
}
#override
void dispose() {
_dateController.dispose();
super.dispose();
}
_handleDatePicker() async {
final DateTime? date = await showDatePicker(
context: context,
initialDate: _date,
firstDate: DateTime(2000),
lastDate: DateTime(2100));
if (date != null && date != _date) {
setState(() {
_date = date;
});
_dateController.text = _dateFormatter.format(date);
}
}
_delete() {
DatabaseHelper.instance.deleteNote(widget.note!.id!);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_)=> HomeScreen()
)
);
widget.updateNoteList!();
}
_submit() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
print("$_title, $_date, $_priority");
Note note = Note(
title: _title,
date: _date,
priority: _priority
);
if (widget.note == null){
note.status = 0;
DatabaseHelper.instance.insertNote(note);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_)=> HomeScreen())
);
}
else{
note.id = widget.note!.id;
note.status = widget.note!.status;
DatabaseHelper.instance.updateNote(note);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_)=> HomeScreen())
);
}
widget.updateNoteList!();
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFF4EEFF),
body: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: SingleChildScrollView(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 40, vertical: 80),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
onTap: () => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => HomeScreen(),
)
),
child: Icon(
Icons.arrow_back,
size: 30,
color: Color(0xFFA6B1E1),
),
),
SizedBox(
height: 20.0,
),
Text(
titleText,
style: TextStyle(
color: Color(0xFF424874),
fontSize: 40,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Form(
key: _formKey,
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: TextFormField(
style: TextStyle(fontSize: 18),
decoration: InputDecoration(
labelText: "Title",
labelStyle: TextStyle(fontSize: 18),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10))),
validator: (input) => input!.trim().isEmpty
? "Please enter a note title"
: null,
onSaved: (input) => _title = input!,
initialValue: _title,
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: TextFormField(
readOnly: true, //hide keyboard
controller: _dateController,
style: TextStyle(fontSize: 18),
onTap: _handleDatePicker,
decoration: InputDecoration(
labelText: "Date",
labelStyle: TextStyle(fontSize: 18),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10))),
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: DropdownButtonFormField(
isDense: true,
icon: Icon(Icons.arrow_drop_down_circle),
iconSize: 22,
iconEnabledColor: Color(0xFF424874),
items: _priorities.map((String priority) {
return DropdownMenuItem(
value: priority,
child: Text(
priority,
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
));
}).toList(),
style: TextStyle(fontSize: 18),
decoration: InputDecoration(
labelText: "Priority",
labelStyle: TextStyle(fontSize: 18),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
)
),
// validator: (input) => _priority == null ? "Please",
onChanged: (value) {
setState(() {
_priority = value.toString();
});
},
value: _priority,
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 20),
height: 60.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30)),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Theme.of(context).primaryColor)
),
child: Text(
btnText,
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: _submit,
),
),
widget.note != null ? Container(
margin: EdgeInsets.symmetric(vertical: 20),
height: 60,
width: double.infinity,
decoration: BoxDecoration(
color: Color(0xFF424874),
borderRadius: BorderRadius.circular(30)
),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Theme.of(context).primaryColor)
),
child: Text("Delete Note",
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
onPressed: _delete,
),
): SizedBox.shrink()
],
),
)
],
),
),
),
),
);
}
}
I am sorry the code is too long.
If you can help me, I will really appreciate it.
Thank you!
This error occurs when you use a bang operator (!) on a nullable instance which wasn't initialized. This operator should only be used when you are sure that the variable cannot be null, I don't recommend using it. Check out this answer

Flutter - put variable value outside a function

i'm trying to show the data i retrieve on a function outside of it (to show in a listview of products) but i cant do it because i cant access the variable.
First I open a dialog where i put the order number, when i click a button on this dialog it runs the following code:
(this function is inside a onPressed).
Future loadProdutos() async{
ProdutosList produtosList =
ProdutosList.fromJson(response.data);
print(produtosList.produtos[1].qtd);
print(produtosList.produtos.length);
}
setState(() {
loadProdutos();
Navigator.pop(context, true);
});
So the data its stored on produtoslist, but when I try to use the produtosList length on the listview (for example) like the example below it cant access the data.
Here
child: ListView.builder(
itemCount: produtosList.produtos.length, <<< //Undefined name 'produtosList'.
Try correcting the name to one that is defined, or defining the name.dart(undefined_identifi
How can I make produtosList accessable from the whole file?
Or to create it outside of the function and use it inside (when i try i cant access the variable inside of the function, maybe because its async).
Heres the full code
class OS extends StatefulWidget {
#override
_OSState createState() => _OSState();
}
class _OSState extends State<OS> {
static _read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'operador';
final value = prefs.getString(key);
print('saved tester $value');
String operadorLogado = value;
return operadorLogado;
}
#override
final _numeroOsController = TextEditingController();
void initState() {
super.initState();
_read();
var produtosList1 = <ProdutoOs>[];
//WidgetsBinding.instance.addPostFrameCallback((_) => _read());
// final prefs = await SharedPreferences.getInstance();
// final key = 'usuario';
// final value = prefs.getString(key);
// print('saved $value');
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("OS Nº xxx"),
actions: <Widget>[
Padding(
padding: EdgeInsets.only(right: 20.0),
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
scrollable: true,
title: Text('BUSCAR OS'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
child: TextFormField(
controller: _numeroOsController,
decoration: InputDecoration(
icon: Icon(Icons.search),
),
),
),
),
actions: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.blue,
onPrimary: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0),
),
),
child: Text("IR"),
onPressed: () async {
Response response;
Dio dio = new Dio();
String url =
'http://192.168.15.2:8090/api/getOs';
response = await dio.post(url, data: {
"numeroos": _numeroOsController.text
});
print(response.statusCode);
jsonDecode(response);
Future loadProdutos() async {
ProdutosList produtosList =
ProdutosList.fromJson(response.data);
print(produtosList.produtos[1].qtd);
print(produtosList.produtos.length);
}
setState(() {
loadProdutos();
Navigator.pop(context, true);
});
},
)
]);
});
},
child: Icon(
Icons.search,
size: 26.0,
),
)),
],
),
body: Column(
children: [
Container(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
children: [
Expanded(
flex: 8,
child: Text(
"CLIENTE:",
style: TextStyle(color: Colors.white),
),
),
Expanded(
flex: 8,
child: Text(
"STATUS:",
style: TextStyle(color: Colors.white),
),
),
],
),
),
),
Container(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 8.0, 0, 8.0),
child: Row(
children: <Widget>[
Expanded(
flex: 2,
child: Text("CÓDIGO",
style: TextStyle(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis),
),
Expanded(
flex: 1,
child: Text(
"QTD",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 3,
child: Text(
"FUNCIONÁRIO",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 4,
child: Text(
"DESCRIÇÃO",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
),
),
Divider(
height: 5.0,
),
Expanded(
child: ListView.builder(
itemCount: 3,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 4.0, 0.0, 4.0),
child: Row(
children: <Widget>[
Expanded(
flex: 2,
child: Text(
"12345",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 1,
child: Text(
"12",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 3,
child: Text("example",
style: TextStyle(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis
),
),
Expanded(
flex: 4,
child: Text(
"DESCRIÇÃO DA PEÇA XXXXXX11111111 XXXXXXX",
style: TextStyle(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis),
),
],
),
);
}),
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
scrollable: true,
title: Text('ADICIONAR PEÇA'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
icon: Icon(Icons.search),
),
),
],
),
),
),
actions: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.blue,
onPrimary: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0),
),
),
child: Text("IR"),
onPressed: () {
// your code
}),
],
);
});
},
child: Icon(Icons.add)),
);
}
}
Declare a local variable in class.
For example:
class PhotosScreen {
final photos = <Photo>[];
Future<void> reloadPhotos() async {
photos.clear();
photos.addAll(await api.getPhotos());
setState(() {});
}
}
In your case (you placed a variable to method, not to class):
var produtosList1 = <ProdutoOs>[];
#override
final _numeroOsController = TextEditingController();
void initState() {
super.initState();
}

I am trying to put gesture dectector in the alert dialog to navigate to next page but the alert box overflows

I am not using any button in alert dialog, so in action how can we prevent the overflow the alert dialog, if am using gesture detector or inkwell to get ontap or onpress function or is there any other method to do it
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
content: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
Container(
child: new GestureDetector(
onTap:(){
Navigator.push(context,
MaterialPageRoute(builder: (context) => ThirdRoute()));
} ,
),
),
]
);
});
}
You are getting overflow error due to GestureDetector used inside actions property of the dialog. If you just want user to tap anywhere on the alertDialog, you can wrap the AlertDialog with GestureDetector. With this, when user taps anywhere on the dialog, it will navigate them to thirdRoute. Working code below:
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return GestureDetector(
child: AlertDialog(
title:
Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
)
],
),
content:
Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 15.0)),
// gradient: LinearGradient(
// colors: <Color>[
// Color(0xDD4a00e0),
// Color(0xFF8e2de2),
// ],
// begin: Alignment.topCenter,
// end: Alignment.bottomCenter,
// ),
actions: <Widget>[]
),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => NextScreen()));
}
);
});
}
Hope this answers your question.
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return GestureDetector(
child: UnicornAlertDialog(
title: Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
content: Text(
'You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[ ]),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => ThirdRoute()));
},
);
});
}
Unicorn alert dialog is used for background-color decoration, and since you cannot have gradient color in normal alert dialog, I used this.
code snippet
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: GestureDetector(
onTap: () { print("on tap title");},
child: Column(
children: <Widget>[
Container(
child: Image.asset('assets/images/background.jpg'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
),
content: GestureDetector(
onTap: () { print("on tap content");},
child: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
]
);
});
}
full code
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
class UnicornAlertDialog extends StatelessWidget {
const UnicornAlertDialog({
Key key,
#required this.gradient,
this.title,
this.titlePadding,
this.titleTextStyle,
this.content,
this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
this.contentTextStyle,
this.actions,
this.backgroundColor,
this.elevation,
this.semanticLabel,
this.shape,
}) : assert(contentPadding != null),
super(key: key);
final Gradient gradient;
final Widget title;
final EdgeInsetsGeometry titlePadding;
final TextStyle titleTextStyle;
final Widget content;
final EdgeInsetsGeometry contentPadding;
final TextStyle contentTextStyle;
final List<Widget> actions;
final Color backgroundColor;
final double elevation;
final String semanticLabel;
final ShapeBorder shape;
#override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
final ThemeData theme = Theme.of(context);
final DialogTheme dialogTheme = DialogTheme.of(context);
final List<Widget> children = <Widget>[];
String label = semanticLabel;
if (title != null) {
children.add(Padding(
padding: titlePadding ?? EdgeInsets.fromLTRB(24.0, 24.0, 24.0, content == null ? 20.0 : 0.0),
child: DefaultTextStyle(
style: titleTextStyle ?? dialogTheme.titleTextStyle ?? theme.textTheme.title,
child: Semantics(
child: title,
namesRoute: true,
container: true,
),
),
));
} else {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
label = semanticLabel;
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
label = semanticLabel ?? MaterialLocalizations.of(context)?.alertDialogLabel;
}
}
if (content != null) {
children.add(Flexible(
child: Padding(
padding: contentPadding,
child: DefaultTextStyle(
style: contentTextStyle ?? dialogTheme.contentTextStyle ?? theme.textTheme.subhead,
child: content,
),
),
));
}
if (actions != null) {
children.add(ButtonTheme.bar(
child: ButtonBar(
children: actions,
),
));
}
Widget dialogChild = IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
if (label != null)
dialogChild = Semantics(
namesRoute: true,
label: label,
child: dialogChild,
);
return Dialog(
backgroundColor: backgroundColor,
gradient: gradient,
elevation: elevation,
shape: shape,
child: dialogChild,
);
}
}
class Dialog extends StatelessWidget {
const Dialog({
Key key,
this.gradient,
this.backgroundColor,
this.elevation,
this.insetAnimationDuration = const Duration(milliseconds: 100),
this.insetAnimationCurve = Curves.decelerate,
this.shape,
this.child,
}) : super(key: key);
final Color backgroundColor;
final double elevation;
final Duration insetAnimationDuration;
final Curve insetAnimationCurve;
final ShapeBorder shape;
final Widget child;
final Gradient gradient;
static const RoundedRectangleBorder _defaultDialogShape =
RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)));
static const double _defaultElevation = 24.0;
#override
Widget build(BuildContext context) {
final DialogTheme dialogTheme = DialogTheme.of(context);
return AnimatedPadding(
padding: MediaQuery.of(context).viewInsets + const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
duration: insetAnimationDuration,
curve: insetAnimationCurve,
child: MediaQuery.removeViewInsets(
removeLeft: true,
removeTop: true,
removeRight: true,
removeBottom: true,
context: context,
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 280.0),
child: Material(
color: backgroundColor ?? dialogTheme.backgroundColor ?? Theme.of(context).dialogBackgroundColor,
elevation: elevation ?? dialogTheme.elevation ?? _defaultElevation,
shape: shape ?? dialogTheme.shape ?? _defaultDialogShape,
type: MaterialType.card,
child: ClipRRect(
borderRadius: _defaultDialogShape.borderRadius,
child: Container(
decoration: BoxDecoration(
gradient: gradient
),
child: child,
),
),
),
),
),
),
);
}
}
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: GestureDetector(
onTap: () { print("on tap title");},
child: Column(
children: <Widget>[
Container(
child: Image.asset('assets/images/background.jpg'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
),
content: GestureDetector(
onTap: () { print("on tap content");},
child: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
]
);
});
}
Future<void> _ackAlert(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Not in stock'),
content: const Text('This item is no longer available'),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
enum ConfirmAction { CANCEL, ACCEPT }
Future<ConfirmAction> _asyncConfirmDialog(BuildContext context) async {
return showDialog<ConfirmAction>(
context: context,
barrierDismissible: false, // user must tap button for close dialog!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Reset settings?'),
content: const Text(
'This will reset your device to its default factory settings.'),
actions: <Widget>[
FlatButton(
child: const Text('CANCEL'),
onPressed: () {
Navigator.of(context).pop(ConfirmAction.CANCEL);
},
),
FlatButton(
child: const Text('ACCEPT'),
onPressed: () {
Navigator.of(context).pop(ConfirmAction.ACCEPT);
},
)
],
);
},
);
}
Future<String> _asyncInputDialog(BuildContext context) async {
String teamName = '';
return showDialog<String>(
context: context,
barrierDismissible: false, // dialog is dismissible with a tap on the barrier
builder: (BuildContext context) {
return AlertDialog(
title: Text('Enter current team'),
content: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
autofocus: true,
decoration: new InputDecoration(
labelText: 'Team Name', hintText: 'eg. Juventus F.C.'),
onChanged: (value) {
teamName = value;
},
))
],
),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop(teamName);
},
),
],
);
},
);
}
enum Departments { Production, Research, Purchasing, Marketing, Accounting }
Future<Departments> _asyncSimpleDialog(BuildContext context) async {
return await showDialog<Departments>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Select Departments '),
children: <Widget>[
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Production);
},
child: const Text('Production'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Research);
},
child: const Text('Research'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Purchasing);
},
child: const Text('Purchasing'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Marketing);
},
child: const Text('Marketing'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Accounting);
},
child: const Text('Accounting'),
)
],
);
});
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: AppBar(
title: Text("Dialog"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(
onPressed: () {
_showDialog(context);
},
child: const Text("Unicon Dialog"),
),
new RaisedButton(
onPressed: () {
_ackAlert(context);
},
child: const Text("Ack Dialog"),
),
new RaisedButton(
onPressed: () async {
final ConfirmAction action = await _asyncConfirmDialog(context);
print("Confirm Action $action" );
},
child: const Text("Confirm Dialog"),
),
new RaisedButton(
onPressed: () async {
final Departments deptName = await _asyncSimpleDialog(context);
print("Selected Departement is $deptName");
},
child: const Text("Simple dialog"),
),
new RaisedButton(
onPressed: () async {
final String currentTeam = await _asyncInputDialog(context);
print("Current team name is $currentTeam");
},
child: const Text("Input Dialog"),
),
],
),
),
);
}
}
void main() {
runApp(new MaterialApp(home: new MyApp()));
}

Categories

Resources