번역 자료 / / 2025. 5. 24. 13:18

[supabase 번역] Supabase와 Flutter 함께 사용하기 (Use Supabase with Flutter)

출처: https://supabase.com/docs/guides/getting-started/quickstarts/flutter


Supabase와 Flutter를 함께 사용하는 방법을 알아봅니다. Supabase 프로젝트를 생성하고, 샘플 데이터를 추가한 뒤, Flutter 앱에서 데이터를 쿼리하는 방법을 안내합니다.


1. Supabase 프로젝트 생성하기

database.new에 접속하여 새로운 Supabase 프로젝트를 생성하세요.

프로젝트가 준비되면 Table Editor로 이동하여 새 테이블을 만들고 데이터를 삽입합니다.

또는, 아래 SQL 스니펫을 프로젝트의 SQL Editor에서 실행할 수 있습니다. 이 코드는 instruments 테이블을 생성하고 샘플 데이터를 추가합니다.

-- 테이블 생성
create table instruments (
  id bigint primary key generated always as identity,
  name text not null
);

-- 샘플 데이터 삽입
insert into instruments (name)
values  ('violin'),
        ('viola'),
        ('cello');

alter table instruments enable row level security;

테이블 데이터를 공개적으로 읽을 수 있도록 RLS 정책 추가

create policy "public can read instruments"
on public.instruments
for select to anon
using (true);

2. Flutter 앱 생성하기

flutter create 명령어를 사용하여 Flutter 앱을 생성하세요. 이미 앱이 있다면 이 단계는 건너뛰어도 됩니다.

flutter create my_app

3. Supabase 클라이언트 라이브러리 설치하기

가장 빠른 시작 방법은 supabase_flutter 클라이언트 라이브러리를 사용하는 것입니다. 이 라이브러리는 Flutter 앱에서 Supabase를 편리하게 사용할 수 있도록 도와줍니다.

Flutter 앱의 pubspec.yaml 파일에 아래와 같이 의존성을 추가하세요.

supabase_flutter: ^2.0.0

4. Supabase 클라이언트 초기화하기

lib/main.dart 파일을 열고, 아래와 같이 main 함수를 수정하여 Supabase를 초기화하세요. (프로젝트 URL과 public API(anon) 키를 입력해야 합니다)

import 'package:supabase_flutter/supabase_flutter.dart';
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Supabase.initialize(
    url: 'YOUR_SUPABASE_URL',
    anonKey: 'YOUR_SUPABASE_ANON_KEY',
  );
  runApp(MyApp());
}

5. 앱에서 데이터 쿼리하기

홈 페이지가 로드될 때 데이터를 가져오고, ListView로 쿼리 결과를 표시하려면 FutureBuilder를 사용하세요. 기본 MyAppMyHomePage 클래스를 아래 코드로 교체하세요.

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Instruments',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _future = Supabase.instance.client
      .from('instruments')
      .select();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: _future,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }
          final instruments = snapshot.data!;
          return ListView.builder(
            itemCount: instruments.length,
            itemBuilder: ((context, index) {
              final instrument = instruments[index];
              return ListTile(
                title: Text(instrument['name']),
              );
            }),
          );
        },
      ),
    );
  }
}

6. 앱 실행하기

원하는 플랫폼에서 앱을 실행하세요! 기본적으로 앱이 웹 브라우저에서 실행됩니다.

flutter run

supabase_flutter는 웹, iOS, Android, macOS, Windows 앱과 호환됩니다. macOS에서 실행하려면 추가 설정이 필요할 수 있습니다.


딥링크(Deep Link) 설정

여러 인증 방식에서는 인증 후 앱으로 리디렉션하기 위해 딥링크 설정이 필요합니다. 모든 플랫폼(웹 포함)에서 딥링크 설정 방법은 Flutter Mobile Guide를 참고하세요.


프로덕션 배포 시 주의사항

Android

프로덕션 환경에서는 Android 앱이 Supabase API와 통신하기 위해 인터넷 권한이 필요합니다. android/app/src/main/AndroidManifest.xml 파일에 아래 라인을 추가하세요.

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
  <!-- Required to fetch data from the internet. -->
  <uses-permission android:name="android.permission.INTERNET" />
  <!-- ... -->
</manifest>

출처: https://supabase.com/docs/guides/getting-started/quickstarts/flutter

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유