iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 1
1
Mobile Development

Flutter 從零開始,Android、iOS一次搞定,重新挑戰。系列 第 1

[Day 1] 萬年老梗,卻很實用之待辦清單。

前面因為一些因素中斷了比賽,決定在此重新參賽。
先前連結

那我們就廢話不多說直接進入,我們的重點待辦清單。

我們先做我們的主頁面,如下圖。

我的習慣會把頁面,放在screens底下,
然後把頁面會使用到的小組件,放在widgets底下

我這邊的 main.dart ,把我們的todos_homepage.dart引入,做簡單的home頁面的渲染。

import 'package:flutter/material.dart';
import './screens/todos_homepage.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: TodosHomepage(),
    );
  }
}

我這邊的 todo_tile.dart,這邊使用StatefulWidget,因為我在這邊存所有的代辦事項資料。

import 'package:flutter/material.dart';
import '../widgets/todo_tile.dart';

class TodosHomepage extends StatefulWidget {
  @override
  _TodosHomepageState createState() => _TodosHomepageState();
}

class _TodosHomepageState extends State<TodosHomepage> {
  List<Map<String, dynamic>> todos = [
    {"title": "Test 1", "description": "abc123 def456", "done": false},
    {"title": "Test 2", "description": "abc123 def456", "done": true},
    {"title": "Test 3", "description": "abc123 def456", "done": false},
    {"title": "Test 4", "description": "abc123 def456", "done": false},
  ];

  void toggleDoneHandler(index, value) {
    setState(() {
      todos[index]['done'] = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Todos'),
      ),
      body: ListView.builder(
        itemCount: todos.length,
        itemBuilder: (ctx, i) => TodoItem(
          title: todos[i]['title'],
          done: todos[i]['done'],
          toggleDone: toggleDoneHandler,
          index: i,
        ),
      ),
    );
  }
}

再來第三個檔案是 todo_tile.dart ,我們這邊有用到dart的 Constructor。

import 'package:flutter/material.dart';

class TodoItem extends StatelessWidget {
  final int index;
  final String title;
  final bool done;
  final Function toggleDone;

  TodoItem({this.title, this.done, this.toggleDone, this.index});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        title,
        style: TextStyle(
          fontSize: 18,
          decoration: done ? TextDecoration.lineThrough : null,
        ),
      ),
      leading: Checkbox(
        activeColor: Colors.lightBlueAccent,
        value: done,
        onChanged: (val) {
          toggleDone(index, val);
        },
      ),
    );
  }
}

這樣就可以建立起第一個主頁面了哦。


下一篇
[Day2] 新增代辦事項實作。
系列文
Flutter 從零開始,Android、iOS一次搞定,重新挑戰。12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
Yanwei Liu
iT邦新手 4 級 ‧ 2019-09-18 21:38:26

加油~

我要留言

立即登入留言