Skip to content

Instantly share code, notes, and snippets.

@davesnowdon
Created December 29, 2022 19:30
Show Gist options
  • Save davesnowdon/7a1c2f0db086caa6dfc064f313fd0e43 to your computer and use it in GitHub Desktop.
Save davesnowdon/7a1c2f0db086caa6dfc064f313fd0e43 to your computer and use it in GitHub Desktop.
ChatGPT: write a simple flutter application that displays a form requesting a person's name and address and stores the result in a local database
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Form Demo',
home: FormPage(),
);
}
}
class FormPage extends StatefulWidget {
@override
_FormPageState createState() => _FormPageState();
}
class _FormPageState extends State<FormPage> {
final _formKey = GlobalKey<FormState>();
String _name;
String _address;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Form Demo'),
),
body: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextFormField(
decoration: InputDecoration(
labelText: 'Name',
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter your name';
}
return null;
},
onSaved: (value) => _name = value,
),
TextFormField(
decoration: InputDecoration(
labelText: 'Address',
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter your address';
}
return null;
},
onSaved: (value) => _address = value,
),
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
saveData();
}
},
child: Text('Save'),
),
],
),
),
),
);
}
void saveData() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, address TEXT)');
});
await database.transaction((txn) async {
int id1 = await txn.rawInsert(
'INSERT INTO Test(name, address) VALUES("$_name", "$_address")');
print('inserted1: $id1');
});
await database.close();
}
}
@davesnowdon
Copy link
Author

flutter pub add sqflite

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment