在上一篇Flutter學習筆記十三——頁面跳轉(zhuǎn)與返回中典蜕,學習了界面跳轉(zhuǎn)與返回捕虽,類似Android中startActivity(intent)
的簡單使用。這節(jié)學習如何跳轉(zhuǎn)時傳值,類似intent
中攜帶bundle
或者直接攜帶extra
躁锡,在第二個界面介紹intent
中的值吆玖。
需求:點擊商品列表后跳轉(zhuǎn)到商品詳情頁筒溃,顯示商品詳情信息。
首先創(chuàng)建商品bean類,包括title
和description
沾乘,還有一個構(gòu)造函數(shù)怜奖。
class Product {
final String title; //商品標題
final String description; //商品描述
Product(this.title, this.description);
}
創(chuàng)建商品列表頁面:
class ProductList extends StatelessWidget {
final List<Product> products;
const ProductList({Key key, @required this.products}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('商品列表'),
centerTitle: true,
backgroundColor: Colors.orangeAccent,
),
body: ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(products[index].title),
leading: Icon(Icons.favorite_border, color: Colors.redAccent),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ProductDetail(product: products[index])));
},
);
}),
);
}
}
頁面跳轉(zhuǎn)使用Navigator.push()
,路由使用MaterialPageRoute()
,其中的ProductDetail(product: products[index])
就是商品詳情頁翅阵,具體代碼如下:
class ProductDetail extends StatelessWidget {
final Product product;
const ProductDetail({Key key, this.product}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('${product.title}'),
),
body: Center(
child: Text('${product.description}'),
),
);
}
}
完整的demo代碼:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: "導航傳值",
home: ProductList(
products:
List.generate(20, (index) => Product('商品$index號', '商品詳情:第$index號商品')),
),
));
}
class ProductList extends StatelessWidget {
final List<Product> products;
const ProductList({Key key, @required this.products}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('商品列表'),
centerTitle: true,
backgroundColor: Colors.orangeAccent,
),
body: ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(products[index].title),
leading: Icon(Icons.favorite_border, color: Colors.redAccent),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ProductDetail(product: products[index])));
},
);
}),
);
}
}
class Product {
final String title;
final String description;
Product(this.title, this.description);
}
class ProductDetail extends StatelessWidget {
final Product product;
const ProductDetail({Key key, this.product}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('${product.title}'),
),
body: Center(
child: Text('${product.description}'),
),
);
}
}