flutter sqlite持久化数据

dependencies:
  path:
  sqflite:
  sqflite_common_ffi:
import ‘dart:io‘;

import ‘package:flutter/material.dart‘;
import ‘package:sqflite_common_ffi/sqflite_ffi.dart‘;
import ‘package:sqflite/sqflite.dart‘;
import ‘package:path/path.dart‘ as path;

Future<Database> database;
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (Platform.isWindows || Platform.isLinux) {
    // Initialize FFI
    sqfliteFfiInit();
    // Change the default factory
    databaseFactory = databaseFactoryFfi;
  }

  database = openDatabase(
    path.join(await getDatabasesPath(), ‘test_database.db‘),
    onCreate: (db, version) {
      return db.execute(
        ‘‘‘
        CREATE TABLE dogs(
          id   INTEGER PRIMARY KEY AUTOINCREMENT, 
          name TEXT NOT NULL
        );
         ‘‘‘,
      );
    },
    version: 1,
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(‘Home Page‘),
      ),
      body: Center(
        child: Column(
          children: [
            RaisedButton(
              onPressed: () async {
                var db = await database;
                var id = await db.insert(‘dogs‘,
                    {‘name‘: ‘[test name] ‘ + DateTime.now().toString()});
                print(id);
              },
              child: Text(‘插入数据‘),
            ),
            RaisedButton(
              onPressed: () async {
                var db = await database;
                var dogs = await db.query(‘dogs‘);
                print(dogs);
              },
              child: Text(‘查看数据‘),
            )
          ],
        ),
      ),
    );
  }
}

flutter sqlite持久化数据

上一篇:jqueryAjax的使用


下一篇:ubuntu 20.04 安装mysql