flutter -------- 頁面跳轉和傳值


在安卓原生開發中,頁面跳轉可以用Intent類來具體實現:

Intent intent =new Intent(MainActivity.this,second.class);

startActivity(intent);

 

頁面的傳值也有很多種

 

Flutter的傳值方式是路由傳值;

例如,我們想傳一些關於我們點擊的ListView條目的信息。
效果圖

    

 

代碼:

final todos = new List<Todo>.generate(
    15,
        (i) => new Todo(
        "我是標題 $i", "我是詳細內容 $i"));


class Todo {
  final String title;
  final String description;

  Todo(this.title, this.description);
}



class ToD extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new FirstScreen(todos);
  }
}


/**
 * 第一個頁面
 */
class FirstScreen extends StatelessWidget {
  final List<Todo> todos;

  FirstScreen(this.todos);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("First Screen"),
      ),
      body: new Center(
        child: new ListView.builder(
            itemCount: todos.length,
            itemBuilder: (context, index) {
              return new ListTile(
                title: new Text(todos[index].title),
                //item的點擊事件 跳轉到新的頁面並攜帶一個Todo對象 傳參就是通過構造函數了
                onTap: () {
                  Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (context) =>
                          new DetailScreen(todo: todos[index])));
                },
              );
            }),
      ),
    );
  }
}

/**
 * 第二個頁面
 */
class DetailScreen extends StatelessWidget {
  final Todo todo;

  //構造函數得到傳值
  DetailScreen({Key key, @required this.todo}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("${todo.title}"),
      ),
      body: new Center(
        child: new GestureDetector(
          child: new Text("${todo.description}"),
          onTap: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

 


免責聲明!

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



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