简体   繁体   English

保存信息到dart flutter数据库拉取信息到listTile

[英]Saving information to dart flutter database and pulling information to listTile

I have an application.我有一个应用程序。 In the application the user will save data.在应用程序中,用户将保存数据。 When you log into a particular page, the record of logging into that page will be saved in the database.当您登录到特定页面时,登录该页面的记录将保存在数据库中。

My problem is this: I examined the sqflite database structure, but I could not understand it.我的问题是:我检查了sqflite数据库结构,但无法理解。 It's a strange building.这是一座奇怪的建筑。 What I need to do is to save data in only 1 column and pull them and put them in listTile .我需要做的是仅将数据保存在 1 列中,然后将它们拉出并放入listTile中。

But as I said, I couldn't do what I wanted because I couldn't understand the sqflite structure.但是就像我说的,我不能如愿以偿,因为我看不懂sqflite的结构。

How can I do it?我该怎么做? How do I use sqflite ?如何使用sqflite

The sqflite library provides the sqlite database to flutter. Your question leads me to assume that you first need to read a bit more about what it is and what is used for. sqflite库提供sqlite数据库到 flutter。你的问题让我假设你首先需要阅读更多关于它是什么以及它的用途。

Once you are familiar with the fundamentals you will be able to grasp the usage of the library fairly easily.熟悉基础知识后,您将能够相当轻松地掌握库的用法。

For your application though, I would suggest going for simpler options.不过,对于您的应用程序,我建议您选择更简单的选项。 You might find a key-value store like shared_preferences , to be easier to grasp and get started with.您可能会发现像shared_preferences这样的键值存储更容易掌握和开始使用。 Just put the data as a JSON list in the store and retrieve it for display when building the ListView.只需将数据作为 JSON 列表放入存储中,并在构建 ListView 时检索它以供显示。

EDIT:编辑:

Use the following as a starting point and take it further as per your requirement:使用以下内容作为起点,并根据您的要求进一步发展:

  import 'package:flutter/material.dart';
  import 'package:sqflite/sqflite.dart';

  Database? db;

  void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    db = await openDatabase(
      'my_db.db',
      version: 1,
      onCreate: (Database db, int version) async {
        await db.execute('CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT)');
      },
    );
    runApp(const MyApp());
  }

  class MyApp extends StatelessWidget {
    const MyApp({Key? key}) : super(key: key);

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

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

    final String title;

    @override
    State<MyHomePage> createState() => _MyHomePageState();
  }

  class _MyHomePageState extends State<MyHomePage> {
    List<Map<String, Object?>>? _records;
    bool _loading = false;
    int nextRecordId = 1;

    @override
    void initState() {
      super.initState();
      getRecords();
    }

    void getRecords() {
      setState(() {
        _loading = true;
      });
      db?.query('Test').then((value) {
        setState(() {
          _records = value;
          _loading = false;
        });
      });
    }

    void _insertRandomRecord() {
      db
          ?.insert(
              'Test',
              {
                'id': '$nextRecordId',
                'name': 'Random record $nextRecordId',
              },
              conflictAlgorithm: ConflictAlgorithm.replace)
          .then((value) {
        nextRecordId++;
        getRecords();
      });
    }

    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: _loading
            ? const Center(
                child: CircularProgressIndicator.adaptive(),
              )
            : ListView.builder(
                itemBuilder: (context, index) {
                  final record = _records![index];
                  return ListTile(
                    title: Text(record['name'] as String),
                  );
                },
                itemCount: _records?.length ?? 0,
              ),
        floatingActionButton: FloatingActionButton(
          onPressed: _insertRandomRecord,
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      );
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM