как решить ошибку синтаксиса флаттера sqlite? - PullRequest
1 голос
/ 26 сентября 2019

bi Я делаю базу данных с помощью sqlite. Я строил базу данных, и у меня возникла проблема.

Это мой полный код экрана:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math';
import 'package:socialapp/model/todo.dart';
import 'package:socialapp/widgets/database_create.dart';



class writeprofile2 extends StatefulWidget {
  writeprofile2({Key key}) : super(key : key);

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

class _writeprofile2State extends State<writeprofile2> {

  final _formKey = GlobalKey<FormState>();
  String _name, _age, _intro;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (context) => Center(
          child: Container(
            child: Container(
              child: Form(
                key: _formKey,
                child: Column(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(top: 70),
                      child: Text(
                        '프로필 작성',
                        style: TextStyle(
                          fontSize: 30,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 10, bottom: 50),
                      child: Container(
                        height: 1,
                        width: MediaQuery.of(context).size.width / 1.4,
                        color: Colors.black26,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 10),
                      child: Container(
                        //이름입력
                        width: MediaQuery.of(context).size.width / 2,
                        height: MediaQuery.of(context).size.height / 20,
                        alignment: FractionalOffset.center,
                        decoration: BoxDecoration(
                          color: Colors.black12,
                          borderRadius:
                          BorderRadius.all(const Radius.circular(20)),
                        ),
                        child: TextFormField(
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                              fontSize: 20,
                            ),
                            border: InputBorder.none,
                            hintText: '이름',
                            prefixIcon: Icon(
                              Icons.person_outline,
                              color: Colors.black,
                            ),
                          ),
                          validator: (input) {
                            if (input.isEmpty) {
                              return '이름을 입력해주세요';
                            }
                          },
                          onSaved: (value)=> _name = value,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 10),
                      child: Container(
                        width: MediaQuery.of(context).size.width / 2,
                        height: MediaQuery.of(context).size.height / 20,
                        alignment: FractionalOffset.center,
                        decoration: BoxDecoration(
                          color: Colors.black12,
                          borderRadius:
                          BorderRadius.all(const Radius.circular(20)),
                        ),
                        child: TextFormField(
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            WhitelistingTextInputFormatter.digitsOnly
                          ],
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                              fontSize: 20,
                            ),
                            border: InputBorder.none,
                            hintText: '나이',
                            prefixIcon: Icon(
                              Icons.label_outline,
                              color: Colors.black,
                            ),
                          ),
                          validator: (val) {
                            if (!isNumber(val)) {
                              return "나이를 입력해주세요";
                            };
                          },
                          onSaved: (value)=> _age = value,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 10),
                      child: Container(
                        //이름입력
                        width: MediaQuery.of(context).size.width / 2,
                        height: MediaQuery.of(context).size.height / 20,
                        alignment: FractionalOffset.center,
                        decoration: BoxDecoration(
                          color: Colors.black12,
                          borderRadius:
                          BorderRadius.all(const Radius.circular(20)),
                        ),
                        child: TextFormField(
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                              fontSize: 20,
                            ),
                            border: InputBorder.none,
                            hintText: '소개',
                            prefixIcon: Icon(
                              Icons.person_outline,
                              color: Colors.black,
                            ),
                          ),
                          validator: (input) {
                            if (input.isEmpty) {
                              return '자기소개';
                            }
                          },
                          onSaved: (value)=> _intro = value,
                        ),
                      ),
                    ),
                    InkWell(
                      onTap: (){
                        Todo newtodo = Todo(name: _name, age: _age, intro: _intro);
                        DBHelper().createData(newtodo);
                        setState(() {
                        });
                      },
                      child: Padding(
                        padding: EdgeInsets.only(top: 50),
                        child: Container(
                          width: MediaQuery.of(context).size.width / 3,
                          height: MediaQuery.of(context).size.height / 20,
                          alignment: FractionalOffset.center,
                          decoration: BoxDecoration(
                            color: const Color.fromRGBO(250, 80, 100, 1),
                            borderRadius:
                            BorderRadius.all(const Radius.circular(30)),
                          ),
                          child: Text(
                            "Next",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 20,
                              fontWeight: FontWeight.w500,
                              letterSpacing: 0.3,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  String randomTodo(){
    final randomNumber = Random().nextInt(4);
    String todo;
    switch(randomNumber){
      case 1:
        todo = 'hello1';
        break;
      case 1:
        todo = 'hello2';
        break;
      case 1:
        todo = 'hello3';
        break;
      default:
        todo = 'default';
        break;
    }
    return todo;
  }
}

bool isNumber(String valueNumber) {
  if (valueNumber == null) {
    return true;
  }
  final n = num.tryParse(valueNumber);
  return n != null;
}

Это мой код задачи:



class Todo {
  int id;
  String name;
  String intro;
  String age;

  Todo({
    this.id,
    this.name,
    this.intro,
    this.age,});

  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
    id: json["id"],
    intro: json["intro"],
    name: json["name"],
    age: json["age"],
  );

  Map<String, dynamic> toJson() =>
      {
        'id' :id,
        'name': name,
        'age': age,
        'intro' : intro,
      };

}

Эта база данных создает код:

import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:socialapp/model/todo.dart';
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';


final String tableName = 'person';

class DBHelper{
  DBHelper._();
  static final DBHelper _db = DBHelper._();
  factory DBHelper() => _db;

  //해당 변수에 데이터베이스 정보 저장
  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, 'PersonProfile.db');

    return await openDatabase(
      path,
      version: 1,
      onOpen: (db) {},
      onCreate: (Database db, int version) async{
        await db.execute('''
        CREATE TABLE $tableName
        id INTEGER PRIMARY KEY,
        name TEXT,
        intro TEXT,
        age TEXT ''');
      },
    );
  }


  createData(Todo todo)async{
    final db = await database;
    var res = await db.insert(tableName, todo.toJson());
    return res;
  }

  //read
  getTodo(int id) async{
    final db = await database;
    var res = await db.query(tableName, where: 'id = ?', whereArgs: [id]);
    return res.isNotEmpty ? Todo.fromJson(res.first) : Null;
  }

//  getAllTodos() async{
//    final db = await database;
//    var res = await db.query(tableNam
//  }
  updateTodo(Todo todo) async{
    final db = await database;
    var res = await db.update(tableName, todo.toJson(),
    where: 'id =?' , whereArgs: [todo.id]);
    return res;
  }

  //Delete
  deleteTodo(int id) async{
    final db = await database;
    db.delete(tableName, where: 'id =?', whereArgs: [id]);
  }

  deleteAllTodos() async{
    final db =await database;
    db.rawDelete("Delete * from $tableName");
  }
}



error code :

> 
> 
>     id INTEGER PRIMARY KEY,
>         name TEXT,
>         intro TEXT,
>         age TEXT flutter: error DatabaseException(Error Domain=FMDatabase Code=1 "near "id": syntax error"
> UserInfo={NSLocalizedDescription=near "id": syntax error}) sql '      
> CREATE TABLE person
>         id INTEGER PRIMARY KEY,
>         name TEXT,
>         intro TEXT,
>         age TEXT ' args []} during open, closing... [VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception:
> DatabaseException(Error Domain=FMDatabase Code=1 "near "id": syntax
> error" UserInfo={NSLocalizedDescription=near "id": syntax error}) sql
> '        CREATE TABLE person
>         id INTEGER PRIMARY KEY,
>         name TEXT,
>         intro TEXT,
>         age TEXT ' args []}
> #0      wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) <asynchronous
> suspension>
> #1      SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:29:7)
> #2      SqfliteDatabaseMixin.safeInvokeMethod (package:sqflite/src/database_mixin.dart:184:15)
> #3      SqfliteDatabaseMixin.invokeExecute (package:sqflite/src/database_mixin.dart:342:12)
> #4      SqfliteDatabaseMixin.txnExecute.<anonymous closure> (package:sqflite/src/database_mixin.dart:334:14)
> #5      SqfliteDatabaseMixin.txnSynchronized (package:sqflite/src/database_mixin.dart:285:26) <asynchronous
> suspension>
> #6      SqfliteDatabaseMixin.txnWriteSynchronized (package:sqflite/src/da<…>




How can i fix this ? 


1 Ответ

2 голосов
/ 26 сентября 2019

Вам необходимо добавить скобки после tableName:

 CREATE TABLE $tableName(
        id INTEGER PRIMARY KEY,
        name TEXT,
        intro TEXT,
        age TEXT)

Проверьте здесь:

http://www.mysqltutorial.org/mysql-create-table/

Также посмотрите пример в sqflite плагин:

  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...