Good afternoon
I'm new to the flutter, and I'm having a hard time, I have a ListView, so I'm trying to do the data persistence with SQflite but I'm not getting anyone could help me.
I have the main pages where LiistView is, I have a form that adds items to the listView.
ListView
`class ListContat extends StatefulWidget {
ListContat({Key key, this.title}) : super(key: key);
final String title;
@override
_ListContatcState createState() => new _ListContatcState();
}
List<User> contact1 = [];
class _ListContatcState extends State<ListContat> {
TextEditingController editingController = TextEditingController();
@override
void initState() {
super.initState();
}
bool order = false; // Ordenar em ordem alfabeica
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.purple,
elevation: 0,
centerTitle: true,
title: Text(
"Contatos",
style: TextStyle(
fontSize: 30,
),
),
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return ListNotificarcao();
},
),
);
},
),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Stack(children: <Widget>[
Container(
height: 50,
width: MediaQuery.of(context).size.width,
alignment: Alignment.bottomCenter,
color: Colors.purple,
),
Padding(
padding: EdgeInsets.only(top: 10),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(40),
topRight: Radius.circular(40),
),
color: Colors.white,
),
height: MediaQuery.of(context).size.height - 100,
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(
top: 20,
left: 2,
right: 2,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.sort_by_alpha),
onPressed: () {
setState(() {
order = !order;
if (order == true) {
contact1.sort(
(a, b) => a.name.compareTo(b.name));
} else {
contact1.sort(
(a, b) => b.name.compareTo(a.name));
}
});
},
),
Container(
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(
bottom: 10, left: 2, right: 40),
width: MediaQuery.of(context).size.width - 80,
height: 50,
child: TextField(
onChanged: (value) {
setState(() {});
},
controller: editingController,
textAlign: TextAlign.center,
textAlignVertical: TextAlignVertical.bottom,
decoration: InputDecoration(
hintText: "Pesquisar Contato",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide:
BorderSide(color: Colors.purple)),
),
),
),
],
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: contact1.length,
itemBuilder: (context, index) {
if (editingController.text.isEmpty) {
final item = contact1[index].name;
return Dismissible(
onDismissed: (direction) {
setState(() {
if (direction ==
DismissDirection.endToStart) {
setState(() {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Notificar(
notificarUser: contact1[index],
),
),
);
});
} else if (direction ==
DismissDirection.startToEnd) {
setState(() {
contact1.removeAt(index);
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(
"$item foi Removido")));
});
}
});
},
background: Container(
color: Colors.red[300],
padding: EdgeInsets.all(10),
alignment: Alignment.centerLeft,
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.delete_sharp,
size: 30,
color: Colors.white,
),
Text(
"Deletar",
style: TextStyle(color: Colors.white),
)
],
),
),
secondaryBackground: Container(
color: Colors.green,
padding: EdgeInsets.all(10),
alignment: Alignment.centerRight,
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.notifications_active,
size: 30,
color: Colors.white,
),
Text(
"Lembrete",
style: TextStyle(color: Colors.white),
)
],
),
),
key: UniqueKey(),
child: Container(
child: ListTile(
leading: IconPerson(),
title: Text(contact1[index].name),
subtitle: Text(contact1[index].phone),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
VisualizarContato(
contact1[index]),
),
);
},
),
),
);
} else if (contact1[index]
.name
.toLowerCase()
.contains(editingController.text)) {
return ListTile(
leading: IconPerson(),
title: Text(contact1[index].name),
subtitle: Text(contact1[index].phone),
);
} else {
return Container();
}
}),
),
],
),
),
)
])
],
),
),
floatingActionButton: FloatingActionButton.extended(
label: Text("Contatos"),
icon: Icon(Icons.add),
backgroundColor: Colors.purple,
onPressed: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return BodyLayout();
},
),
);
},
),
);
}
}`
form that adds items to the listView.
`final formkey = GlobalKey<FormState>();
var nome, telefone, endereco, email, cidade, uf, numero;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cadastro"),
centerTitle: true,
backgroundColor: Colors.purple,
leading: IconButton(
icon: new Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return ListContat();
},
),
);
},
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.save),
onPressed: () {
if (formkey.currentState.validate()) {
setState(() {
formkey.currentState.save();
contact1.add(
User(
//image: ('$_image').toString(),
name: '$nome',
phone: '$telefone',
email: '$email',
address: '$endereco',
city: '$cidade',
number: '$numero',
uf: '$uf',
),
);
});
Navigator.of(context).pop();
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return ListContat();
},
));
}
},
),
],
),
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
padding: EdgeInsets.all(15),
child: Form(
key: formkey,
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10),
child: Container(
padding: EdgeInsets.all(5),
height: 100,
width: 100,
child: image == null ? IconPerson() : Image.file(image),
),
),
Padding(
padding: EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton.extended(
heroTag: "bt3",
label: Text("Camera"),
hoverColor: Colors.cyan,
icon: Icon(Icons.camera_alt_outlined),
onPressed: () => getImageCamera(),
),
Divider(
endIndent: 10,
),
FloatingActionButton.extended(
heroTag: "bt4",
label: Text("Galeria"),
hoverColor: Colors.cyan,
icon: Icon(Icons.photo),
onPressed: () => getImageGalley(),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
style: TextStyle(fontWeight: FontWeight.bold),
keyboardType: TextInputType.name,
onSaved: (value) => nome = (value),
validator: (value) {
if (value.trim().isEmpty) {
return "Digite um Nome ";
}
return null;
},
decoration: InputDecoration(
labelText: "Nome:",
contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(30),
)),
),
),
Padding(
padding: EdgeInsets.all(7),
child: TextFormField(
style: TextStyle(fontWeight: FontWeight.bold),
keyboardType: TextInputType.phone,
onSaved: (value) => telefone = (value),
validator: (value) {
if (value.trim().isEmpty) {
return "Digite um Telefone";
}
return null;
},
decoration: InputDecoration(
labelText: "Telefone:",
contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(30),
)),
inputFormatters: [
new LengthLimitingTextInputFormatter(11),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
style: TextStyle(fontWeight: FontWeight.bold),
keyboardType: TextInputType.emailAddress,
onSaved: (value) => email = (value),
decoration: InputDecoration(
labelText: "E-mail:",
contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(30),
),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: MediaQuery.of(context).size.width - 140,
child: TextFormField(
style: TextStyle(fontWeight: FontWeight.bold),
keyboardType: TextInputType.text,
onSaved: (value) => cidade = (value),
decoration: InputDecoration(
labelText: "Cidade:",
contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(30),
),
),
),
),
Divider(
endIndent: 10,
),
Container(
width: 80, //MediaQuery.of(context).size.width,
child: TextFormField(
style: TextStyle(fontWeight: FontWeight.bold),
onSaved: (value) => uf = (value),
validator: (String arg) {
if (arg.length >= 3) {
return 'Ex: Ce';
} else {
return null;
}
},
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: "UF:",
contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(30),
),
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: MediaQuery.of(context).size.width - 140,
child: TextFormField(
style: TextStyle(fontWeight: FontWeight.bold),
onSaved: (value) => endereco = (value),
decoration: InputDecoration(
labelText: "Endereço:",
contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(30),
),
),
),
),
Divider(
endIndent: 10,
),
Container(
width: 80, //MediaQuery.of(context).size.width,
child: TextFormField(
style: TextStyle(fontWeight: FontWeight.bold),
keyboardType: TextInputType.streetAddress,
onSaved: (value) => numero = (value),
decoration: InputDecoration(
labelText: "N°:",
contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(30),
),
),
),
),
],
),
),
],
),
),
),
),
);Model
class User {
int id;
String name;
String email;
String phone;
String city;
String uf;
String address;
String number;
String image;
User({
this.id,
this.name,
this.phone,
this.email,
this.city,
this.uf,
this.address,
this.number,
this.image,
});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'name': name,
'phone': phone,
'email': email,
'city': city,
'uf': uf,
'address': address,
'number': number,
'image': image,
};
return map;
}
User.fromMap(Map<String, dynamic> map) {
id = map['id'];
name = map['name'];
phone = map['phone'];
email = map['email'];
city = map['city'];
uf = map['ufB'];
address = map['address'];
number = map['number'];
image = map['image'];
}
}`
DataBase
`import 'package:Agenda_de_Lembretes/contatos/UserCampos/user.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'dart:async';
class DatabaseHelp {
static DatabaseHelp _databaseHelp;
static Database _database;
//Usada para definir as colunas da tabela
String contatotable = 'contato';
String colId = 'id';
String colNome = 'nome';
String colphone = 'phone';
String colemail = 'email';
String colcity = 'city';
String coluf = 'ufB';
String coladdress = 'address';
String colnumber = 'number';
String colimage = 'image';
//Construtor nomeado para criar initância da classe
DatabaseHelp._createInstance();
factory DatabaseHelp() {
if (_databaseHelp == null) {
databaseHelp = DatabaseHelp.createInstance();
}
return _databaseHelp;
}
Future<Database> get database async {
if (_database == null) {
_database = await initializeDatabase();
}
return _database;
}
Future<Database> initializeDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'contatos.db';
var contatosDatabase =
await openDatabase(path, version: 1, onCreate: _createDb);
return contatosDatabase;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
'CREATE TABLE $contatotable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colNome TEXT, $coladdress TEXT, $colcity TEXT, $colemail TEXT, $colnumber INTEGER, $colphone INTEGER, $coluf TEXT, $colimage TEXT)');
}
Future<int> insertContato(User contato) async {
Database db = await this.database;
var resultado = await db.insert(contatotable, contato.toMap());
return resultado;
}
Future<User> getContato(int id) async {
Database db = await this.database;
List<Map> maps = await db.query(contatotable,
columns: [
colId,
colNome,
coladdress,
colcity,
colemail,
colnumber,
colphone,
coluf,
colimage
],
where: "$colId = ?",
whereArgs: [id]);
if (maps.length > 0) {
return User.fromMap(maps.first);
} else {
return null;
}
}
Future<List<User>> getContatos() async {
Database db = await this.database;
var resultado = await db.query(contatotable);
List<User> lista = resultado.isNotEmpty
? resultado.map((c) => User.fromMap(c)).toList()
: [];
return lista;
}
Future<int> updateContato(User contato) async {
var db = await this.database;
var resultado = await db.update(contatotable, contato.toMap(),
where: '$colId = ?', whereArgs: [contato.id]);
return resultado;
}
Future<int> deleteContatos(int id) async {
var db = await this.database;
int resultado =
await db.delete(contatotable, where: '$colId = ?', whereArgs: [id]);
return resultado;
}
Future<int> getCount() async {
Database db = await this.database;
List<Map<String, dynamic>> x =
await db.rawQuery('SELECT COUNT(*) from $contatotable');
int resultado = Sqflite.firstIntValue(x);
return resultado;
}
Future close() async {
Database db = await this.database;
db.close();
}
}`