[Flutter] Responsive UI

saewoohan·2023년 8월 3일
1

Flutter

목록 보기
3/12
post-thumbnail

🙊 문제인식

  • 앱을 개발하면 여러 디바이스를 지원하기 위해 디바이스에 대응하여 각 UI의 크기를 재조정해야한다. 이때, MediaQuery를 통해서 각 Widget들의 크기를 정의 할 수 있으나 상당히 귀찮다..
  • 특히 flutter는 IOS, Android 두 OS 모두 지원해야 하기 때문에 디바이스 마다의 UI차이가 더욱 부각되는 점이 있다..!!

🔑 flutter_screenutil

https://pub.dev/packages/flutter_screenutil

  • 가히 혁명적인 package라고 할 수 있다.
  • 간단히 package를 다운받고 디자인 기준이 되는 device의 width, height만 입력해주면 반응형 UI의 80프로는 완성이다!!

 📦 사용법

1. package 다운

flutter_screenutil package를 다운 받는다. 그렇다면 pubspec.yaml 파일에 해당 종속성이 추가 된다.

dependencies:
  flutter:
    sdk: flutter
  # add flutter_screenutil
  flutter_screenutil: ^{latest version}

2. package import

  • main.dart 파일에 해당 package를 import해준다.
import 'package:flutter_screenutil/flutter_screenutil.dart';

3. MaterialApp 수정

void main() => runApp(MyApp());

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

  @override
  Widget build(BuildContext context) {
    //Set the fit size (Find your UI design, look at the dimensions of the device screen and fill it in,unit in dp)
    return ScreenUtilInit(
      designSize: const Size(360, 690),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context , child) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'First Method',
          // You can use the library anywhere in the app even in theme
          theme: ThemeData(
            primarySwatch: Colors.blue,
            textTheme: Typography.englishLike2018.apply(fontSizeFactor: 1.sp),
          ),
          home: child,
        );
      },
      child: const HomePage(title: 'First Method'),
    );
  }
}
  • MaterialApp을 ScreenUtilInit으로 감싸준다.
  • 이때, designSize에 디자인 기준이 되는 device의 width, height를 입력해준다.
  • 이러면 기본적인 설정은 모두 끝났다. (class에 있는 나머지 속성들은 필요에 따라 추가하면 된다.)

4. 사용법

Container(
  width: 50.w,
  height:200.h
  decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
      ),
)
  • width와 height, radius는 해당 코드와 같이 간단히 숫자 뒤에 w(width)혹은 h(height), r(radius)을 붙여주면 된다!
    Text(
      '16sp,if data is not set in MediaQuery,my font size will change with the system.',
      style: TextStyle(
        color: Colors.black,
        fontSize: 16.sp,
      ),
    ),
  • fontSize도 마찬가지로 숫자뒤에 .sp를 붙여주면 된다!
  • 위와 같은 형태로 반응형 UI가 필요한 모든 widget들의 크기, 글꼴 등을 조절해주면 된다.
  • padding같은 값도 이와 같은 형태로 설정 할 수 있기에 혁명적이다..! (사실상 width, height를 가지는 모든 것들이 가능한 것 같다.)
ex) EdgeInsets.only(left:8.w,right:8.w)

💡 유의사항

  • 이렇게 반응형 UI를 만들었지만 시스템 자체 글꼴 크기로 인해서 overflow 혹은 원하는 UI디자인이 제대로 구현되지 않을 수 있다.
  • 이를 해결하기 위해서 system fontsize에 무관하게 동작하도록 설정하는 것이 권장된다.
MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'Flutter_ScreenUtil',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  builder: (context, widget) {
    return MediaQuery(
      ///Setting font does not change with system font size
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: widget,
    );
  },
  home: HomePage(title: 'FlutterScreenUtil Demo'),
),

0개의 댓글