본문 바로가기
플러터/플러터 개념

[Day6] UI Basics 3 - Flutter for SwiftUI Developers 번역

by 인생여희 2023. 11. 9.

[Day6] UI Basics 3 - Flutter for SwiftUI Developers 번역

 

목차

* Navigating between pages 

* Manually pop back 

* Navigating to another app

 

 

Navigation

 


이 부분에서는 앱의 페이지를 어떻게 이동하는지 설명합니다. 삽입(push)과 제거(pop) 메커니즘 등에 관해서 설명합니다.


Navigating between pages(페이지간 탐색)

개발자는 내비게이션 라우트라(navigation routes)고 불리는 다양한 페이지들로  iOS앱과 macOS앱을 구축합니다.

SwiftUI에서 NavigationStack이 페이지들의 스택을 표현합니다.

아래 예제에서 사람들의 목록을 나타내는 앱을 생성합니다.

사람의 상세정보를 새로운 내비게이션 링크에 나타내기 위해서 해당 사람 Row를 탭 합니다.

NavigationStack(path: $path) {
      List {
        ForEach(persons) { person in
          NavigationLink(
            person.name,
            value: person
          )
        }
      }
      .navigationDestination(for: Person.self) { person in
        PersonView(person: person)
      }
    }



만약 복잡한 이동이 없는 작은 플러터앱을 개발한다면, 네임드 라우터(named routes)와 함께 Navigation 라우터를 사용하세요.
내비게이션 라우터를 정의한 다음, 이름으로 네비게이션 라우터를 호출하세요.

// Defines the route name as a constant
 // so that it's reusable.
 const detailsPageRouteName = '/details';

 class App extends StatelessWidget {
   const App({
     super.key,
   });

   @override
   Widget build(BuildContext context) {
     return CupertinoApp(
       home: const HomePage(),
       // The [routes] property defines the available named routes
       // and the widgets to build when navigating to those routes.
       routes: {
         detailsPageRouteName: (context) => const DetailsPage(),
       },
     );
   }
 }



아래 샘플에서 mockPersons()을 사용해서 사람정보 목록을 생성했습니다.

1. 사람 Row를 탭 하면 pushNamed() 메서드를 이용해서 사람의 정보 페이지를 Navigator로 push 합니다.

   ListView.builder(
   itemCount: mockPersons.length,
   itemBuilder: (context, index) {
     final person = mockPersons.elementAt(index);
     final age = '${person.age} years old';
     return ListTile(
       title: Text(person.name),
       subtitle: Text(age),
       trailing: const Icon(
         Icons.arrow_forward_ios,
       ),
       onTap: () {
         // When a [ListTile] that represents a person is
         // tapped, push the detailsPageRouteName route
         // to the Navigator and pass the person's instance
         // to the route.
         Navigator.of(context).pushNamed(
           detailsPageRouteName,
           arguments: person,
         );
       },
     );
   },
 ),



2. 각 사람의 세부 정보를 표시하는 DetailsPage 위젯을 정의합니다.
Flutter에서는 새 경로로 이동할 때 위젯에 파라미터(인수)를 전달할 수 있습니다. ModalRoute.of()를 사용하여 인수를 추출합니다:

class DetailsPage extends StatelessWidget {
   const DetailsPage({super.key});

   @override
   Widget build(BuildContext context) {
     // Read the person instance from the arguments.
     final Person person = ModalRoute.of(
       context,
     )?.settings.arguments as Person;
     // Extract the age.
     final age = '${person.age} years old';
     return Scaffold(
       // Display name and age.
       body: Column(children: [Text(person.name), Text(age)]),
     );
   }
 }



보다 고급 탐색 및 라우팅 요구 사항을 만들려면 go_router와 같은 라우팅 패키지를 사용하세요.
자세히 알아보려면 내비게이션 및 라우팅을 확인하세요.

go_router : https://pub.dev/packages/go_router
내비게이션 및 라우팅 : https://docs.flutter.dev/ui/navigation


Manually pop back

SwiftUI에서는 dismiss 환경 값(environment value)을 사용하여 이전 화면으로 돌아갈 수 있습니다.

Button("Pop back") {
        dismiss()
}



Flutter에서 Navigator 클래스의 pop() 함수를 사용합니다:

TextButton(
  onPressed: () {
    // This code allows the
    // view to pop back to its presenter.
    Navigator.of(context).pop();
  },
  child: const Text('Pop back'),
),



Navigating to another app

SwiftUI에서는 openURL 환경 변수를 사용하여 다른 애플리케이션의 URL을 엽니다.


Flutter에서 url_launcher 플러그인을 사용합니다.

CupertinoButton(
  onPressed: () async {
    await launchUrl(
      Uri.parse('https://google.com'),
    );
  },
  child: const Text(
    'Open website',
  ),
),



Themes, styles, and media

당신은 적은 노력으로 플러터앱을 스타일링할 수 있습니다.
라이트모드, 다크모드 전환과 텍스트 디자인, UI 컴포넌트 변환을 포함해서 다양한 스타일링을 할 수 있습니다.
이번 섹션에서는 어떻게 앱을 스타일링하는지를 설명합니다.

Using dark mode

SwiftUI에서는 뷰에서 preferredColorScheme() 함수를 호출하여 다크 모드를 사용합니다.

Flutter에서는 앱 수준에서 밝기 및 어둡기 모드를 제어할 수 있습니다. 밝기 모드를 제어하려면 App 클래스의 테마 속성을 사용합니다:

CupertinoApp(
  theme: CupertinoThemeData(
    brightness: Brightness.dark,
  ),
  home: HomePage(),
);



Styling text

SwiftUI에서는 수정자 함수를 사용하여 텍스트 스타일을 지정합니다. 예를 들어 텍스트 문자열의 글꼴을 변경하려면 font() 수정자를 사용합니다:

Text("Hello, world!")
  .font(.system(size: 30, weight: .heavy))
  .foregroundColor(.yellow)



Flutter에서 텍스트에 스타일을 지정하려면 Text 위젯의 스타일 매개변수 값으로 TextStyle 위젯을 추가합니다.

Text(
  'Hello, world!',
  style: TextStyle(
    fontSize: 30,
    fontWeight: FontWeight.bold,
    color: CupertinoColors.systemYellow,
  ),
),



Styling buttons

SwiftUI에서는 수정자 함수를 사용하여 버튼의 스타일을 지정합니다.

Button("Do something") {
    // do something when button is tapped
  }
  .font(.system(size: 30, weight: .bold))
  .background(Color.yellow)
  .foregroundColor(Color.blue)
}



Flutter에서 버튼 위젯의 스타일을 지정하려면 자식의 스타일을 설정하거나 버튼 자체의 속성을 수정합니다.

아래 예제:
1.CupertinoButton의 색상 속성에 버튼의 색상을 설정합니다.
2. 하위 Text 위젯의 색상 속성에 버튼 텍스트 색상을 설정합니다.

child: CupertinoButton(
  color: CupertinoColors.systemYellow,
  onPressed: () {},
  padding: const EdgeInsets.all(16),
  child: const Text(
    'Do something',
    style: TextStyle(
      color: CupertinoColors.systemBlue,
      fontSize: 30,
      fontWeight: FontWeight.bold,
    ),
  ),
),