'Flutter: I can't pull data with Mysql1
I recently started Flutter. I want to make a simple contacts application with "mysql1" but I failed to pull the data. I installed the MySQL plugin in VS Code and I can see the table I created, but the application always returns "no data". After some research, I learned that it is better to do it with the API. But I still want to know why this is not working. Thank you.
Model: contact_model.dart
class ContactModel {
int? id;
String? name;
String? lastName;
String? phoneNumber;
ContactModel(this.id, this.name, this.lastName, this.phoneNumber);
}
View: homepage.dart
import 'package:flutter/material.dart';
import '../models/contact_model.dart';
import '../../products/utility/database_helper.dart';
import 'add_data.dart';
// ignore: must_be_immutable
class HomePage extends StatefulWidget {
bool state = false;
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final DatabaseOperations _databaseOperations = DatabaseOperations();
List<ContactModel> allData = [];
@override
void initState() {
super.initState();
fetchData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("IContacts"),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
const Duration(seconds: 3);
// ignore: avoid_print
print("value");
Navigator.push<bool>(
context, MaterialPageRoute(builder: (context) => data_add()));
},
),
body: Container(
child: allData.isNotEmpty
? ListView.builder(
itemCount: allData.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(allData[index].name ?? "error"),
subtitle: Text(allData[index].phoneNumber ?? "error"),
leading: Text(allData[index].id.toString()),
trailing: IconButton(
tooltip: "Delete Person",
icon: const Icon(Icons.delete),
onPressed: () async {}),
);
})
: const Text("no data")),
);
}
void fetchData() async {
allData = await _databaseOperations.fetchData();
setState(() {});
}
}
DatabaseHelper: database_helper.dart
import 'package:mysql1/mysql1.dart';
import '../../feature/models/contact_model.dart';
class DatabaseOperations {
final String _host = 'localhost';
final int _port = 3306;
final String _user = 'root';
final String _password = '';
final String _db = 'contact_app';
DatabaseOperations();
Future fetchData() async {
try {
final connect = await MySqlConnection.connect(ConnectionSettings(
host: _host, port: _port, user: _user, password: _password, db: _db));
List<ContactModel> myList = [];
var dataList = await connect.query('SELECT * FROM `contacts_db`');
for (var item in dataList) {
myList.add(ContactModel(
item["id"], item["name"], item["lastName"], item["phoneNumber"]));
}
await connect.close();
return myList;
} catch (e) {}
}
Future<bool> addData(
{required String name,
required String lastName,
required String phoneNumber}) async {
try {
final connect = await MySqlConnection.connect(
ConnectionSettings(
host: _host,
port: _port,
user: _user,
password: _password,
db: _db),
);
await connect.query(
"insert into contacts_db (name,lastName,phoneNumber) values (?,?,?)",
[name, lastName, phoneNumber]);
await connect.close();
return true;
} catch (e) {
return false;
}
}
Future<bool> updateData(
{required int id,
required String name,
required String lastName,
required String phoneNumber}) async {
try {
final connect = await MySqlConnection.connect(
ConnectionSettings(
host: _host,
port: _port,
user: _user,
password: _password,
db: _db),
);
await connect.query(
"update contacts_db set name=? , lastName=? , phoneNumber = ? where id = ?",
[name, lastName, phoneNumber, id]);
await connect.close();
return true;
} catch (e) {
return false;
}
}
Future<bool> deleteData({required int id}) async {
try {
final connect = await MySqlConnection.connect(
ConnectionSettings(
host: _host,
port: _port,
user: _user,
password: _password,
db: _db),
);
await connect.query('delete from contacts_db where id=?', [id]);
await connect.close();
return true;
} catch (e) {
return false;
}
}
}
Debug Console :
E/flutter (27691): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'List<ContactModel>'
E/flutter (27691): #0 _HomePageState.fetchData
package:rehber_uygulamasi/…/view/homepage.dart:58
E/flutter (27691): <asynchronous suspension>
E/flutter (27691):
Application finished.
Exited (sigterm)
**_HomePageSate.fetchData package:rehber_uygulamasi...homepage.dart:58 :
void fetchData() async {
allData = await _databaseOperations.fetchData();
setState(() {});
}
Solution 1:[1]
My assumption: Your fetchData() method is throwing an exception. You are catching it, but not doing anything with it. When throwing the exception your method basically returns nothing, hence the error is saying type 'Null' is not a subtype of type 'List<ContactModel>'.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | puelo |
