import 'package:flutter/material.dart';
import 'package:postgres/postgres.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: PostgresDataScreen(),
);
}
}
class PostgresDataScreen extends StatefulWidget {
@override
_PostgresDataScreenState createState() => _PostgresDataScreenState();
}
class _PostgresDataScreenState extends State<PostgresDataScreen> {
List<Map<String, dynamic>> _dataList = [];
Future<void> _getData() async {
final connection = PostgreSQLConnection(
'your_host',
5432,
'your_database',
username: 'your_username',
password: 'your_password',
);
try {
await connection.open();
final results = await connection.query('SELECT * FROM your_table');
setState(() {
_dataList = results.map((row) => row.toMap()).toList();
});
} catch (e) {
print('Error while connecting to the database: $e');
setState(() {
_dataList = [];
});
} finally {
await connection.close();
print('Connection closed');
}
}
@override
void initState() {
super.initState();
_getData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('PostgreSQL Flutter App'),
),
body: _dataList.isEmpty
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: _dataList.length,
itemBuilder: (context, index) {
final rowData = _dataList[index];
return ListTile(
title: Text('ID: ${rowData['id']}'),
subtitle: Text('Name: ${rowData['name']}'),
);
},
),
);
}
}