flutter_프로젝트/0_초보_코드모음

flutter 코드모음 - sqflite db 에 값 추가

studyapps 2025. 5. 29. 23:51

db를 만들었으면 db에 값을 넣는 것을 진행 해 본다.

 

textfield 를 만들어서 거기에 입력받은 값을 버튼을 누르면 db에 저장한다.

 

텍스트 필드에서 값을 받아올 변수를 생성한다.

  TextEditingController txt_controller = TextEditingController();
 

 

텍스트 필드를 만들어준다

TextField(
            decoration: const InputDecoration(
              labelText: 'Enter text',
            ),

            controller:
                txt_controller, // Uncomment if you want to use the controller
          )

 

입력을 하는 버튼도 하나 만들어 준다.

입력 내용은 텍스트 필드에 있는 텍스트이지만 일단 변수만 만들어 본다.

txt_controller 라는 controller 에서 text속성을 가져오면 된다.

그리고 입력이 완료되면 텍스트 필드를 비워준다 (clear)

          ElevatedButton(
            onPressed: () async {
              String inputText = txt_controller.text;
              txt_controller.clear(); // Clear the text field after insertion
            },
            child: const Text("Insert Data"),
          ),

 

입력을 하려면 db에 입력하는 함수를 만들어서 버튼에 연결 해 줘야 한다.

_insert라는 함수를 만든다. 함수가 호출되면 value 값을 받아와서 데이터 베이스에 insert한다.

Future<void> _insert(String value) async {
    await _database?.insert(
      'test',
      {'text': value},
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

 

conflictAlgorithm: ConflictAlgorithm.replace 은 sqflite 에서 DB에 데이터를 삽입할 때, 기본키가 이미 존재하는 경우 어떻게 처리할지 지정하는 옵션이다. 충돌이 발생하면, 기존 데이터를 새 데이터로 덮어쓴다.

 

우리가 만든 db는 아래와 같다

db.execute(
        'CREATE TABLE test (id INTEGER PRIMARY KEY, text TEXT)',
      );

 

db파일이름이 별도로 있고, db이름은 test이며 id ,(키값), text라는 필드가 있다.

그래서 'test' db에 'text' 필드에 value로 넘겨받은 값을 넣는 것이다.

 

버튼에 연결된 함수를 수정 해 준다

          ElevatedButton(
            onPressed: () async {
              String inputText = txt_controller.text;
              await _insert(inputText);
              txt_controller.clear(); // Clear the text field after insertion
            },
            child: const Text("Insert Data"),
          ),
 

 

 

이렇게 하면 db에 텍스트 필드에 입력한 값이 저장된다! ? 맞아?