728x90

Flutter에서 screen 과 page 는 route 로 불린다.
Route는 Android의 Activity, iOS의 ViewController와 동일하다. 
Flutter에서는 Route 역시 위젯이다.

새로운 route로 이동은 Navigator를 사용한다.
Navigator.push()를 사용하여 두 번째 route로 전환한다.
Navigator.pop()을 사용하여 첫 번째 route로 되돌아 온다.

 

import 'package:link2me/route.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
 
  @override
  State<MyApp> createState() => _MyAppState();
}
 
class _MyAppState extends State<MyApp> {
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirstRoute(),
    );
  }
}

 

 

import 'package:flutter/material.dart';
 
class FirstRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Route'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Open route'),
          onPressed: () {
            // 눌렀을 때 두 번째 route로 이동
            // push() 메서드는 Route를 Navigator에 의해 관리되는 route 스택에 추가
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondRoute()),
            );
          },
        ),
      ),
    );
  }
}
 
class SecondRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Route"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // pop() 메서드는 route 스택에서 현재 Route를 제거
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}
 

자료 출처 : https://docs.flutter.dev/cookbook/navigation/navigation-basics

 

Navigator.pushNamed()를 통한 화면전환

출처 : https://docs.flutter.dev/cookbook/navigation/named-routes

Route 정의하기
다음으로, MaterialApp 생성자에 initialRoute와 routes 이름의 추가 프로퍼티를 제공하여 route를 정의한다.
initialRoute 프로퍼티는 앱의 시작점을 나타내는 route를 정의하고, 
routes 프로퍼티는 이용가능한 named route와 해당 route로 이동했을 때 빌드될 위젯을 정의한다.

 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {
        // "/" Route로 이동하면, FirstRoute 위젯을 생성한다.
        '/': (context) => FirstRoute(),
        // "/second" route로 이동하면, SecondRoute 위젯을 생성한다.
        '/second': (context) => SecondRoute(),
      },
      //home: FirstRoute(),
    );
  }

 

import 'package:flutter/material.dart';
 
class FirstRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Route'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Open route'),
          onPressed: () {
            // 눌렀을 때 두 번째 route로 이동
            // push() 메서드는 Route를 Navigator에 의해 관리되는 route 스택에 추가
            // Navigator.push(
            //   context,
            //   MaterialPageRoute(builder: (context) => SecondRoute()),
            // );
 
            // Named route를 사용하여 두 번째 화면으로 전환
            Navigator.pushNamed(context, '/second');
          },
        ),
      ),
    );
  }
}
 
class SecondRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Route"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // pop() 메서드는 route 스택에서 현재 Route를 제거
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

 

 

 

화면 전환 코드가 포함된 예제이다.

import 'package:flutter/material.dart';
import 'package:myapp/listview_demo1.dart';
 
class CallsfloatBtn extends StatefulWidget {
  const CallsfloatBtn({Key? key}) : super(key: key);
 
  @override
  _CallsfloatBtnState createState() => _CallsfloatBtnState();
}
 
class _CallsfloatBtnState extends State<CallsfloatBtn> {
  int _counter = 0;
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center, // 중앙정렬
          children: <Widget>[
            Text(
              '당신은 버튼을 눌렀어요 :',
              softWrap: false// 텍스트가 영역을 넘어갈 경우 줄바꿈 여부
              style: Theme.of(context).textTheme.headline5,
            ),
            Text(
              '$_counter 번',
              style: TextStyle(fontSize: 25),
            ),
            ElevatedButton(
              child: Text('화면 이동'),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => ListView_Demo1())
                );
              },
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.teal),
                  padding: MaterialStateProperty.all(EdgeInsets.all(15)),
                  textStyle: MaterialStateProperty.all(TextStyle(fontSize: 14))),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
 
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
}
 

 

 

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
 
// Android Studio 에서 stless 를 입력후 엔터키를 치면
// 자동완성 코드가 작성되고 클래스명을 지정하면 된다.
class ListView_Demo1 extends StatelessWidget {
  const ListView_Demo1({Key? key}) : super(key: key);
 
  // ListView 위젯 정적 데모
  static const List<String> _data = [
    'Mercury(수성)',
    'Venus(금성)',
    'Earth(지구)',
    'Mars(화성)',
    'Jupiter(목성)',
    'Saturn(토성)',
    'Uranus(천왕성)',
    'Neptune(해왕성)',
    'Pluto(명왕성)',
  ];
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: CupertinoNavigationBar(
          leading: CupertinoNavigationBarBackButton(
            onPressed: () => Navigator.of(context).pop(),
          ),
          middle: Text('쿠퍼티노 UI'),
          trailing: GestureDetector(
            child: Icon(CupertinoIcons.search),
            onTap: (){},
          ),
          backgroundColor: CupertinoColors.activeGreen,
          border: Border(
              bottom:BorderSide(
                  width: 1,
                  color: CupertinoColors.activeGreen,
                  style: BorderStyle.solid
              )
          ),
        ),
        //body: _buildStaticListView(),
        body: _buildStaticListViewSeperated(),
      ),
    );
  }
 
  Widget _buildStaticListView() {
    return ListView.builder(
      itemCount: _data.length,
      itemBuilder: (BuildContext _context, int i) {
        return ListTile(
          title: Text(_data[i],
              style: TextStyle(
                fontSize: 23,
              )),
          trailing: Icon(
            Icons.favorite_border,
          ),
        );
      },
    );
  }
 
  Widget _buildStaticListViewSeperated() {
    return ListView.separated(
      itemCount: _data.length,
      itemBuilder: (BuildContext _context, int i) {
        return ListTile(
          title: Text(_data[i],
              style: TextStyle(
                fontSize: 23,
              )),
          trailing: Icon(
            Icons.favorite_border,
          ),
        );
      },
      separatorBuilder: (BuildContext _context, int i) {
        return const Divider();
      },
    );
  }
}
 
728x90
블로그 이미지

Link2Me

,