Flutter 頁面入棧和出棧


Docs

demo

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: RaisedButton(
        child: Text('跳轉到 screen2'),
        onPressed: () {
          Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => Screen2(),
          ));
        },
      ),
    ));
  }
}

class Screen2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          child: Text('back'),
          onPressed: () {
            Navigator.of(context).pop(null);
          },
        ),
      ),
    );
  }
}

配置 routes 跳轉

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Ajnauw',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      routes: <String, WidgetBuilder>{
        '/a': (BuildContext context) => MyPage(title: 'page A'),
        '/b': (BuildContext context) => MyPage(title: 'page B'),
        '/c': (BuildContext context) => MyPage(title: 'page C'),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<String> _pages = <String>['/a', '/b', '/c'];
  String togoPage = '/b';

  _handleRadioValueChange(String nv) {
    setState(() {
      togoPage = nv;
    });
  }

  // 返回一個小widget
  Widget _generagorRadio(String pageName) {
    return GestureDetector(
      onTap: () {
        _handleRadioValueChange(pageName);
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey[200],
        ),
        margin: EdgeInsets.only(top: 8.0),
        child: Row(
          children: <Widget>[
            Radio(
              value: pageName,
              onChanged: _handleRadioValueChange,
              groupValue: togoPage,
            ),
            Text(pageName),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('demo'),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: 8.0, right: 8.0),
            child: Column(
              children: _pages
                  .map((String pageName) => _generagorRadio(pageName))
                  .toList(),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 8.0, right: 8.0, top: 8.0),
            child: RaisedButton(
              onPressed: () {
                // 點擊觸發事件,頁面入棧
                Navigator.pushNamed(context, togoPage);
              },
              color: Theme.of(context).primaryColor,
              child: Text('跳轉新頁面 $togoPage'),
            ),
          ),
        ],
      ),
    );
  }
}

class MyPage extends StatelessWidget {
  final String title;

  MyPage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Text(title),
      ),
    );
  }
}

動畫頁面路勁轉換

          Navigator.of(context).push(
            PageRouteBuilder(
              transitionDuration: Duration(milliseconds: 500),
              pageBuilder: (context, animation, secondaryAnimation) =>
                  Screen2(),
              transitionsBuilder:
                  (context, animation, secondaryAnimation, child) {
                var begin = Offset(0.0, 1.0);
                var end = Offset.zero;
                var curve = Curves.ease;

                var tween = Tween(begin: begin, end: end);
                var curvedAnimation = CurvedAnimation(
                  parent: animation,
                  curve: curve,
                );
                return SlideTransition(
                  position: tween.animate(curvedAnimation),
                  child: child,
                );
              },
            ),
          );

pushReplacement

通過推送給定路線替換導航器的當前路線,然后在新路線完成動畫輸入后處置前一路線

Navigator.of(context).pushReplacement(
  MaterialPageRoute(builder: (context) => HomePage())
)

設置404頁面

    MaterialApp(
      navigatorObservers: [routeObserver],
      home: HomePage(),
      title: 'home',
      onUnknownRoute: (RouteSettings settings) {
        return MaterialPageRoute(
          builder: (context) => Title(
            title: '頁面未找到',
            color: Theme.of(context).primaryColor,
            child: Scaffold(
              appBar: AppBar(),
              body: Center(child: Text('404')),
            ),
          ),
          settings: RouteSettings(
            name: 'not-found',
          ),
        );
      },
    );

設置不同的進場/出場動畫

Navigator.of(context).push(
  PageRouteBuilder(
      transitionDuration: Duration(milliseconds: 500),
      pageBuilder: (context, animation, secondaryAnimation) =>
          Scaffold(
            backgroundColor: Colors.red,
            body: Center(child: Text('page 2')),
            floatingActionButton: FloatingActionButton(
              child: Icon(Icons.backspace),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ),
      transitionsBuilder: (
        context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
        child,
      ) {
        return SlideTransition(
          position: Tween(
            // 關鍵點
            begin: animation.status == AnimationStatus.reverse
                ? const Offset(-1.0, -1.0)
                : const Offset(1.0, 1.0),
            end: Offset.zero,
          ).animate(animation),
          child: child,
        );
      }),
);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM