Flutter 官网例子

首页
跳转界面
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.red, // 主题颜色
      ),
      home: ContactListWidget(),
    );
  }
}

class ContactListWidget extends StatefulWidget {
  @override
  createState() => ContactListState();
}

class ContactListState extends State {
  // 数据
  var contacts = [
    "Roy",
    "Lily",
    "Leo",
    "Kiven",
    "Capatin",
    "Charles",
    "Mark",
    "Bill",
    "Vincent",
    "William",
    "Joseph",
    "James",
    "Henry",
    "Gary",
    "Martin"
  ];
  var collects = []; // 收藏的数据
  final fontStyle = const TextStyle(fontSize: 18.0);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("联系人列表"),
        actions: [
          IconButton(
            icon: Icon(Icons.list),
            iconSize: 40.0,
            onPressed: pushAction,
          ),
        ],
      ),
      body: buildContactList(),
    );
  }

  // 构建列表
  Widget buildContactList() {
    return ListView.separated(
      padding: const EdgeInsets.all(10.0),
      itemCount: contacts.length,
      separatorBuilder: (context,index) {
        return Divider(color: Colors.black26,height: 0.5,);
      },
      itemBuilder: (context, index) {
        return buildRow(contacts[index]);
      },
    );
  }

  // 构建Row
  Widget buildRow(String contact) {
    bool alreadyCollect = collects.contains(contact); // 是否收藏
    return ListTile(
      leading: Icon(Icons.people,size: 40,),
      title: Text(
        contact,
        style: fontStyle,
      ),
      subtitle: Text("详细信息",style: fontStyle,),
      trailing: Icon(
        alreadyCollect ? Icons.favorite : Icons.favorite_border,
        color: alreadyCollect ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (alreadyCollect) {
            collects.remove(contact);
          } else {
            collects.add(contact);
          }
        });
      },
    );
  }

  // 跳转
  void pushAction() {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) {
        var titles = collects.map((title) {
          return ListTile(
            title: Text(
              title,
              style: fontStyle,
            ),
          );
        });

        var divided =
            ListTile.divideTiles(tiles: titles, context: context).toList();
        return Scaffold(
          appBar: AppBar(
            title: Text(
              "收藏列表",
              style: fontStyle,
            ),
          ),
          body: ListView(
            children: divided,
          ),
        );
      }),
    );
  }
}

你可能感兴趣的:(Flutter 官网例子)