首页 > 建站教程 > APP开发,混合APP >  Flutter笔记63:最简单的路由传参正文

Flutter笔记63:最简单的路由传参

Flutter路由传参:利用两个页面构造函数接受参数实现最简单的路由传参:
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: '最简单的路由传参',
    home: ProductList(
      products:
          List.generate(20, (index) => Product('商品 $index', '这是商品${index}的描述')),
    ),
  ));
}

//单个商品数据结构
class Product {
  final String title;
  final String description;
  Product(this.title, this.description);
}

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: (BuildContext context, int index) {
            return ListTile(
              title: Text(products[index].title),
              onTap: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) =>
                            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 Scaffold(
      appBar: AppBar(
        title: Text(product.title),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Text(product.description),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pop(context);
        },
        child: Icon(Icons.backup),
      ),
    );
  }
}