聲明數(shù)據(jù)結(jié)構(gòu)類
Dart中可以使用類來抽象一個(gè)數(shù)據(jù),比如我們模仿一個(gè)商品信息叁执,有商品標(biāo)題和商品描述篙悯。我們定義了一個(gè)Product類,里邊有兩個(gè)字符型變量夕凝,title和description宝穗。
title:是商品標(biāo)題。
description: 商品詳情描述
class Product{
final String title; //商品標(biāo)題
final String description; //商品描述
Product(this.title,this.description);
}
構(gòu)建一個(gè)商品列表:
void main(){
runApp(MaterialApp(
title:'數(shù)據(jù)傳遞案例',
home:ProductList(
products:List.generate(
20,
(i)=>Product('商品 i')
),
)
));
}
ProductList自定義組件的代碼:
class ProductList extends StatelessWidget{
final List<Product> products;
ProductList({Key key,@required this.products}):super(key:key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:Text('商品列表')),
body:ListView.builder(
itemCount:products.length,
itemBuilder: (context,index){
return ListTile(
title:Text(products[index].title),
onTap:(){
}
);
},
)
);
}
}
全部代碼:
import 'package:flutter/material.dart';
//傳遞的數(shù)據(jù)結(jié)構(gòu),也可以理解為對(duì)商品數(shù)據(jù)的抽象
class Product{
final String title; //商品標(biāo)題
final String description; //商品描述
Product(this.title,this.description);
}
void main(){
runApp(MaterialApp(
title:'數(shù)據(jù)傳遞案例',
home:ProductList(
products:List.generate(
20,
(i)=>Product('商品 i')
),
)
));
}
class ProductList extends StatelessWidget{
final List<Product> products;
ProductList({Key key,@required this.products}):super(key:key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:Text('商品列表')),
body:ListView.builder(
itemCount:products.length,
itemBuilder: (context,index){
return ListTile(
title:Text(products[index].title),
onTap:(){
Navigator.push(
context,
MaterialPageRoute(
builder:(context)=>new ProductDetail(product:products[index])
)
);
}
);
},
)
);
}
}
class ProductDetail extends StatelessWidget {
final Product product;
ProductDetail({Key key ,@required this.product}):super(key:key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title:Text('{product.description}'),)
);
}
}