main.dart
import 'package:flutter/material.dart';
void main(){
return runApp(MyApp());
}
class ProductInfo{
final String title;
final String description;
ProductInfo(this.title,this.description);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '导航栏传值',
home: Scaffold(
appBar: AppBar(title: Text('导航栏传值'),),
body: ProductList(
products: List.generate(20, (i)=>ProductInfo("title$i", "description")),
),
),
);
}
}
class ProductList extends StatelessWidget{
final List<ProductInfo> products;
ProductList({Key key, @required this.products}):super(key:key);
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: products.length,
itemBuilder: (context,index){
return ListTile(
title: Text(products[index].title),
//列表被点击
onTap: (){
print(products[index].title);
// Navigator.push(
// context,
// MaterialPageRoute(
// builder:(context) => ProductDetail(product: products[index])
// ));
_jumpToDetail(context,index);
},
);
},
);
}
_jumpToDetail(BuildContext context,int index) async{
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetail(product: products[index])
)
);
//使用showSnackBar显示弹窗
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(result),
duration: Duration(seconds: 1),
)
);
}
}
class ProductDetail extends StatelessWidget {
final ProductInfo product;
ProductDetail({Key key, @required this.product}):super(key:key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(product.title)),
body: Center(
child: RaisedButton(
child: Text("点击返回"),
onPressed: (){
Navigator.pop(context,'反向传值result=${product.title}');
},
),
)
);
}
}
重点
1.快速创建模型对象
List.generate(20, (i)=>ProductInfo("title$i", "description"))
2.快速创建ListView列表
ListView.builder(
itemCount: products.length,
itemBuilder: (context,index){
return ListTile(
title: Text(products[index].title),
//列表被点击
onTap: (){
print(products[index].title);
Navigator.push(
context,
MaterialPageRoute(
builder:(context) => ProductDetail(product: products[index])
));
},
);
},
);
3.导航Navigator push
Navigator.push(
context,
MaterialPageRoute(
builder:(context) => ProductDetail(product: products[index])
));
},
4.导航pop
//不含参数
Navigator.pop(context);
//包含回调参数
Navigator.pop(context,'反向传值result=${product.title}');
5.反向传值
//通过result接收返回值
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetail(product: products[index])
)
);
6.SnackBar显示回调值
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(result),
duration: Duration(seconds: 1),
)
);