我如何 select 来自 sqflite table 的数据并显示(显示)它?

How do I select data from an sqflite table and display(show) it?

我正在尝试制作一个测验应用程序。 我想要的是在屏幕上显示我的文本数据。 我试过使用 Futurebuilder or TextEditingController 但我不知道我能做什么..

这是我的所有代码。

首先,我为我的 sample_quiz.dart

构建了一个 class
class SampleQuiz {
 
  final int QN;
  final String Question;
  final String BodyQ;
  final String FirstQ;
  final String SecondQ;
  final String ThirdQ;
  final String ForthQ;
  final String FifthQ;

  SampleQuiz({
  this.QN, this.Question, this.BodyQ,this.FirstQ, this.SecondQ, this.ThirdQ, this.ForthQ, this.FifthQ,
  });

//Map to Json
  factory SampleQuiz.fromJson(Map<String, dynamic> json) => new SampleQuiz(
        QN: json['QN'],
        Question: json['Question'],
        BodyQ: json['BodyQ'],
        FirstQ: json['FirstQ'],
        SecondQ: json['SecondQ'],
        ThirdQ: json['ThirdQ'],
        ForthQ: json['ForthQ'],
        FifthQ: json['FifthQ'],
      );

  Map<String, dynamic> toJson() => {
    'QN':QN,
    'Question': Question,
    'BodyQ': BodyQ,
    'FirstQ': FirstQ,
    'SecondQ': SecondQ,
    'ThirdQ': ThirdQ,
    'ForthQ': ForthQ,
    'FifthQ': FifthQ,
  };
}

而且,我为 sample_quiz.db 制作了一个 db_helper.dart (我在 pubspec.yaml 上上传了 assets/sample_quiz.db

import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'sample_quiz.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

class DBHelper {
  static final String tablename = 'sample_quiz';
  DBHelper._();

  static final DBHelper instance = DBHelper._();

  factory DBHelper() => instance;
  static Database _database;

  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await initDB();
    return _database;
  }

  initDB() async {
   Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, 'sample_quiz.db');
    ByteData data = await rootBundle.load(join("assets", "sample_quiz.db"));
    List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    await new File(path).writeAsBytes(bytes);

    return await openDatabase(
        path,
        version: 1,
        onCreate: (db, version) async {
          await db.execute('''CREATE TABLE $tablename (
          QN INTEGER PRIMARY KEY,
          Question TEXT,
          BodyQ TEXT,
          FirstQ TEXT,
          SecondQ TEXT,
          ThirdQ TEXT,
          ForthQ TEXT,
          FifthQ TEXT,
          )''');
        },
        onUpgrade: (db, oldVersion, newVersion) {});
  }

  Future<int> insert(Map<String, dynamic> column) async {
    Database db = await instance.database;
    return await db.insert(tablename, column);
  }

  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(tablename);
  }

//This is for Title of Question number 1
  Future<List<Map<String, dynamic>>> queryQuestion() async {
    Database db = await instance.database;
    return await db.query('SELECT Question FROM $tablename WHERE QN = ?', whereArgs: [1]);
  }

//This is for Body of Question number 1
  getQuestion() async {
    final db = await database;
    var res = await db.query('SELECT BodyQ FROM sample_quiz WHERE QN=?', whereArgs: [1]);
    return res.isNotEmpty ? true : false ;
  }

(我有所有的 CRUD,但它们似乎与我的问题无关,所以我跳过它们。)

最后,这是我的 main.dart。 我先搭建脚手架。 我只是认为这将是工作变更 Text() 部分,但事实并非如此。

请检查 >>FutureBuilder<< 使用 queryQuestion() 的部分。 另一部分仅作为示例,我可以应用其他部分。 我写的都是以防万一

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo sqlite quiz'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),

        body: Center(
          child: ListView(
            children: <Widget>[
              Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    child: Text(
                      '$QN',
                      style: Theme
                          .of(context)
                          .textTheme
                          .headline3,
                    ),
                  ),

                  Expanded(
                    child: FutureBuilder(
                      future: DBHelper.queryQuestion(),
                      builder: (context, AsyncSnapshot<String> snapshot) {
                        return Text( '${snapshot.data.toStringAsFixed(1)}',
                          style: Theme
                              .of(context)
                              .textTheme
                              .bodyText1,                        );
                      }
                    ),
                  ),
                ],
              ),

              Center(
                child: Text(
                  '<Body>',
                  style: Theme
                      .of(context)
                      .textTheme
                      .caption,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10, right: 10, bottom: 8),
                child: Text(
                  //$bodyQ
                padding: const EdgeInsets.all(8),
                decoration:
                BoxDecoration(border: Border.all(color: Colors.green)),
              ),

...(there are multiple choice section, but they are same with above)...
 }//Scaffold

//it was for Question Number(QN) but it never work for me.
  _QuestionNumber() async {
    Database db = await DBHelper.instance.database;
    List<Map> qn =
    await db.rawQuery('SELECT QN FROM sample_quiz WHERE QN=?', [1]);
    qn.forEach((row) {
      return qn;
    });
  }
}//_MyHomePageState

请忽略 main.dart 中的那种 Text($QN) 东西。粗略地写了,因为我厌倦了修复它们。

我需要做的是select一个数据单元格并显示出来! 请帮我。 谢谢!

首先您需要创建一个对象才能访问 DBhelper。

DBHelper _dbHelper ;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _dbHelper = new DBHelper();
  }

快照应 return 与未来方法相同的类型 returning。

Container(
            child: FutureBuilder(
                future: _dbHelper.queryQuestion(),
                builder: (context, AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                  return Text(
                    '${snapshot.data}',
                    style: Theme.of(context).textTheme.bodyText1,
                  );
                }),
          ),