0% found this document useful (0 votes)
18 views

Database Flutter Program

Uploaded by

riha soft
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Database Flutter Program

Uploaded by

riha soft
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import 'package:flutter/material.

dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SQLite Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'SQLite Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {


MyHomePage({Key? key, required this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


final TextEditingController _nameController = TextEditingController();
final TextEditingController _ageController = TextEditingController();

Future<Database> _initDatabase() async {


return openDatabase(
join(await getDatabasesPath(), 'person_database.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE persons(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT,
age INTEGER)",
);
},
version: 1,
);
}

Future<void> _insertPerson(String name, int age) async {


final Database db = await _initDatabase();

await db.insert(
'persons',
{'name': name, 'age': age},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _nameController,
decoration: InputDecoration(hintText: 'Enter name'),
),
TextField(
controller: _ageController,
decoration: InputDecoration(hintText: 'Enter age'),
keyboardType: TextInputType.number,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
final name = _nameController.text;
final age = int.tryParse(_ageController.text) ?? 0;
await _insertPerson(name, age);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Person added to database')),
);
_nameController.clear();
_ageController.clear();
},
child: Text('Add Person'),
),
],
),
),
);
}
}

You might also like