iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 9
0

之前我們的側欄,做了群組的功能,但是選擇還沒有任何的改變。
今天我們就讓他選擇了會有反應吧!

第一步,我把它移植到Provider

import 'package:flutter/material.dart';

class Group {
  final id;
  final IconData icon;
  final Color color;
  final String name;
  Group({this.id, this.color, this.icon, this.name});
}

class Groups with ChangeNotifier {
  List<Group> _items = [
    Group(
      id: 1,
      color: Colors.redAccent,
      name: 'important',
      icon: Icons.important_devices,
    ),
    Group(
      id: 2,
      color: Colors.black,
      name: 'Normal',
      icon: Icons.menu,
    )
  ];

  List<Group> get items {
    return [..._items];
  }
}

第二步,我要在代辦清單加入Group ID這樣我才能確定他應該在哪個群組。

class Todo with ChangeNotifier {
  final int id;
  final int groupId;
  final String title;
  final String description;
  bool done;

  Todo({this.id, this.groupId, this.title, this.description, this.done});
  // ...
}

class Todos with ChangeNotifier {
  int selectedGroupId = 1;
  List<Todo> _items = [
    Todo(id: 1, groupId: 1, title: "Test1", description: "abc123", done: false),
    Todo(id: 2, groupId: 2, title: "Test2", description: "abc123", done: false),
    Todo(id: 3, groupId: 1, title: "Test3", description: "abc123", done: false),
    Todo(id: 4, groupId: 1, title: "Test4", description: "abc123", done: true),
    Todo(id: 5, groupId: 1, title: "Test5", description: "abc123", done: false),
    Todo(id: 6, groupId: 2, title: "Test6", description: "abc123", done: true),
    Todo(id: 7, groupId: 2, title: "Test7", description: "abc123", done: false),
    Todo(id: 8, groupId: 2, title: "Test8", description: "abc123", done: false),
  ];

  List<Todo> get items {
    return [..._items];
  }

  List<Todo> get getByGroupId {
    return _items.where((todo) => todo.groupId == selectedGroupId).toList();
  }

  void setSelectedGroupId(int selectId) {
    selectedGroupId = selectId;
    notifyListeners();
  }

  // ...
}

第三步,調整組建囉~ lib/widgets/app_drawer.dart

// ...
ListTile(
  leading: Icon(groupsProvider.items[i].icon),
  title: Text(
    groupsProvider.items[i].name,
    style: TextStyle(
      color: groupsProvider.items[i].color,
      fontSize: 16,
    ),
  ),
  onTap: () {
    Provider.of<Todos>(context)
        .setSelectedGroupId(groupsProvider.items[i].id);
    Navigator.of(context).pop();
  },
);
// ...

onTap 原本是空白的,選擇時更改 selectedGroupId

第四部,改變渲染 lib/widgets/todo_homepage.dart

// ...
body: ListView.builder(
    itemCount: todosProvider.getByGroupId.length,
    itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
      value: todosProvider.getByGroupId[i],
      child: TodoTile(slidableController: slidableController),
    ),
  ),
// ...

改變成拿那個groupId所屬的代辦事項,這樣就好囉~


上一篇
[Day8] Flutter 移動端儲存方案 SQLite。
下一篇
[Day10] Flutter 新增群組Modal。
系列文
Flutter 從零開始,Android、iOS一次搞定,重新挑戰。12

尚未有邦友留言

立即登入留言