2021年7月23日 星期五

[又重學flutter]切版

1. 使用vs code

2. cmd + shift + p

3. flutter: new application project

產生的專案如下

https://github.com/fenturechance/flutterPractice2021/tree/791d1356873e1444320be261f79935929e20f933

(vs code設定了Format on save,才能自動編排code)

(不過我的前端專案我不想這樣做,所以有設"beautify.ignore": ["*.js", "*.vue", "*.html", "*.css"])

把lib的main.dart內容刪光光

剩下


1. 等比例圖片

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text(
          'My App',
          style: TextStyle(fontSize: 12.0, color: Colors.amber),
        ),
      ),
      body: Column(
        //垂直排列
        children: [
          Padding(
            padding: EdgeInsets.all(10.0), //內距
            child: AspectRatio(
              aspectRatio: 16 / 9, //大小固定16比9
              child: Container(
                child: Image.network('https://fakeimg.pl/250x100',
                    fit: BoxFit.cover), //撐大圖片
              ),
            ),
          ),
          Text('test Image')
        ],
      ),
    ),
  ));
}
呈現效果


2. List.generate

import 'package:flutter/material.dart';

void main() {
  List<String> textList = ['aaa', 'bbb', 'ccc'];
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text(
          'My App',
          style: TextStyle(fontSize: 12.0, color: Colors.amber),
        ),
      ),
      body: Column(
        //垂直排列
        children: List.generate(textList.length, (index) {
        return _generateText(textList[index]);
      })
      ),
    ),
  ));
}

Widget _generateText(String text) {
  return Text(text);
}

3. 專案夾內圖片AssetImage

//lib/main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text(
          'My App',
          style: TextStyle(fontSize: 12.0, color: Colors.amber),
        ),
      ),
      body: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(10.0),
            child: AspectRatio(
              aspectRatio: 16 / 9,
              child: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('assets/images/fake250_100.png'),
                      fit: BoxFit.cover),
                ),
              ),
            ),
          )
        ],
      ),
    ),
  ));
}

//assets/images/fake250_100.png //下載檔案放進去

//pubspec.yml
...
flutter:
  uses-material-design: true
  assets: 
    - assets/images/ #指定assets資料夾

4. Column > MainAxisAlignment.center

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('test')),
        body: Container(
          color: Colors.blueAccent,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('test'),
              Text('test'),
              Text('test'),
              Text('test'),
              Text('test'),
            ],
            ),
        ),
  )));
}

5. Column > MainAxisAlignment.end

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('test')),
        body: Container(
          color: Colors.blueAccent,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
            ),
        ),
  )));
}

6. 用center包住container

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text('test')),
          body: Center(
            child: Container(
              color: Colors.blueAccent,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
        ),
            ),
          ))));
}

6-1. 使用container的alignment

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      home: Scaffold(
    appBar: AppBar(title: Text('test')),
    body: Container(
      alignment: Alignment.center,
      color: Colors.blueAccent,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text('test'),
          Text('test'),
          Text('test'),
          Text('test'),
          Text('test'),
        ],
      ),
    ),
  )));
}

7. Column > MainAxisAlignment.spaceAround

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text('test')),
          body: Center(
            child: Container(
              color: Colors.blueAccent,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
        ),
            ),
          ))));
}

7. Column > MainAxisAlignment.spaceBetween

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text('test')),
          body: Center(
            child: Container(
              color: Colors.blueAccent,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
        ),
            ),
          ))));
}

8. Column > MainAxisAlignment.spaceEvenly

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text('test')),
          body: Center(
            child: Container(
              color: Colors.blueAccent,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
        ),
            ),
          ))));
}

9. Column > MainAxisSize.min

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text('test')),
          body: Center(
            child: Container(
              color: Colors.blueAccent,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
        ),
            ),
          ))));
}

10. Row > MainAxisSize.min

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text('test')),
          body: Center(
            child: Container(
              color: Colors.blueAccent,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
        ),
            ),
          ))));
}

11. Row > MainAxisAlignment.center

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text('test')),
          body: Center(
            child: Container(
              color: Colors.blueAccent,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
        ),
            ),
          ))));
}

11. Row > MainAxisAlignment.spaceBetween

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text('test')),
          body: Center(
            child: Container(
              color: Colors.blueAccent,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                  Text('test'),
                ],
        ),
            ),
          ))));
}

12. SafeArea

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          body: Container(
              child: SafeArea(
                child: Column(
                  children: [Text('test')],
                ),
  )))));
}

13. SizedBox

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          body: Container(
              child: SafeArea(
                child: Column(
                  children: [
                    SizedBox(height: 100.0), Text('test')],
                ),
  )))));
}

14. Shadow / Offset

顏色方面

0x代表16進位表示

ff代表不透明度全滿

ff代表紅色全滿

00代表綠色沒有

00代表藍色沒有

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
      home: Scaffold(
          body: Container(
              child: SafeArea(
                child: Column(
                  children: [
                    Text(
                      'test',
                      style: TextStyle(
                          fontSize: 50.0,
                          fontWeight: FontWeight.w900,
                          shadows: [
                            Shadow(color: Color(0xffff0000), offset: Offset(1.0, 1.0))
                          ]),
                    )
                  ],
                ),
  )))));
}

15. MediaQuery.of(context).size (螢幕寬高)

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(home: HomePage()));
}

class HomePage extends StatelessWidget {
  HomePage();
  
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
          body: Container(
            color: Colors.blue,
            width: size.width / 2,
            child: SafeArea(
              child: Column(
                children: [
                  Text('test')],
    ),
            )));
  }
}

16. ListView.builder / Expanded

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(home: HomePage()));
}
class HomePage extends StatelessWidget {
  HomePage();
  
  Widget build(BuildContext context) {
    return Scaffold(
          body: Container(
            child: SafeArea(
              child: Column(children: [
                Expanded(
                    child: ListView.builder(
                        itemCount: 20,
                        itemBuilder: (BuildContext context, int idx) {
                          return Text('Demo${idx}');
                        }))
              ]),
    )));
  }
}

16. ListView.separated / Divider

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(home: HomePage()));
}
class HomePage extends StatelessWidget {
  HomePage();
  
  Widget build(BuildContext context) {
    return Scaffold(
          body: Container(
            child: SafeArea(
                child: Column(children: [
                    Expanded(
                        child: ListView.separated(
                            itemBuilder: (BuildContext context, int idx) {
                              return Text('demo${idx}');
                            },
                            separatorBuilder: (BuildContext context, int idx) {
                              return Divider(
                                color: Colors.grey,
                              );
                            },
                            itemCount: 30))
                  ]))));
  }
}

17. ListTile

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(home: HomePage()));
}
class HomePage extends StatelessWidget {
  HomePage();
  
  Widget build(BuildContext context) {
    return Scaffold(
          body: Container(
            child: SafeArea(
                child: Column(children: [
                    Expanded(
                        child: ListView.builder(
                            itemBuilder: (BuildContext context, int idx) {
                              return ListTile(
                                title: Row(
                                  children: [
                                    Expanded(child: Text('左邊佔滿最多')),
                                    Text('右邊')],
                                ),
                              );
                            },
                            itemCount: 30))
                  ]))));
                }
}

18. BoxDecoration / BorderRadius

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      home: Scaffold(
          body: SafeArea(
    child: Center(
      child: Container(
        // color: Colors.blue,
        width: 100,
        height: 100,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0), color: Colors.red),
      ),
    ),
  ))));
}


19. DecorationImage / BoxFit.fitWidth

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      home: Scaffold(
          body: SafeArea(
    child: Center(
      child: Container(
        // color: Colors.blue,
        width: 300,
        height: 300,
        decoration: BoxDecoration(
            image: DecorationImage(
                image: NetworkImage('https://fakeimg.pl/250x100/'),
                fit: BoxFit.fitWidth),
            borderRadius: BorderRadius.circular(10.0),
            color: Colors.red),
            
      ),
    ),
  ))));
}

20. BoxFit.cover

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      home: Scaffold(
          body: SafeArea(
    child: Center(
      child: Container(
        // color: Colors.blue,
        width: 300,
        height: 300,
        decoration: BoxDecoration(
            image: DecorationImage(
                image: NetworkImage('https://fakeimg.pl/250x100/'),
                fit: BoxFit.cover), //用短邊去對
            borderRadius: BorderRadius.circular(10.0),
            color: Colors.red),
            
      ),
    ),
  ))));
}

21. BoxFit.contain

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      home: Scaffold(
          body: SafeArea(
    child: Center(
      child: Container(
        // color: Colors.blue,
        width: 300,
        height: 300,
        decoration: BoxDecoration(
            image: DecorationImage(
                image: NetworkImage('https://fakeimg.pl/250x100/'),
                fit: BoxFit.contain), //用長邊去對
            borderRadius: BorderRadius.circular(10.0),
            color: Colors.red),
      ),
    ),
  ))));
}

22. BoxFit.fill

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      home: Scaffold(
          body: SafeArea(
    child: Center(
      child: Container(
        // color: Colors.blue,
        width: 300,
        height: 300,
        decoration: BoxDecoration(
            image: DecorationImage(
                image: NetworkImage('https://fakeimg.pl/250x100/'),
                fit: BoxFit.fill), //全部塞滿
            borderRadius: BorderRadius.circular(10.0),
            color: Colors.red),
      ),
    ),
  ))));
}

23. Wrap / Axis.vertical(直書排列)

import 'package:flutter/material.dart';

void main() {
  String string = '今天是我一歲生日';
  List<Text> list = string.split('').map((s) => Text(s)).toList();

  runApp(MaterialApp(
      home: Scaffold(
          body: SafeArea(
    child: Center(
        child: Wrap(
      direction: Axis.vertical,
      children: list,
    )),
  ))));
}

24. LieanrGradient / Alignment.topRight (漸層)

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [Colors.blue, Colors.blue.shade200])),
      ),
    ),
  ));
}

25. Flexible / Text的softWrap

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
        body: SafeArea(
      child: Row(
        children: [
          Text('我是左邊'),
          Flexible(
            child: Text(
              '我是右邊的一段假文字: 垃圾第一個紀念著名十大做法,遊戲滿足,性格做到某個,比如五年價格專區停止應當該公司看看就是讀書,外面你也不能下載想要聽說排行先進性是的提高高手,轉載心裡我真就有對手無線,新臺幣可用責任加拿大手指楠雅處於不行利潤整理辦公新年,討論區地說重大之間發生請教,一。',
              softWrap: true,
            ),
          )
        ],
      ),
    )),
  ));
}

26. TextField / TextEditingController

結果:

輸入框內容改變時:onChange會觸發

輸入框上按Enter時:onSubmit會觸發

按按鈕時:可從controller把值帶過去

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _inputController = TextEditingController();
  String onChangeValue = '';
  String onSubmitValue = '';
  String buttonClickValue = '';
  
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
      child: Center(
          child: Column(
        children: [
          TextField(
            controller: _inputController,
            onChanged: (value) {
              setState(() {
                onChangeValue = value;
              });
            },
            onSubmitted: (value) {
              setState(() {
                onSubmitValue = value;
              });
            },
            decoration: InputDecoration(
                filled: true,
                fillColor: Colors.blue.shade400,
                border: InputBorder.none,
                hintText: "請輸入",
                hintStyle: TextStyle(color: Colors.yellow)),
          ),
          GestureDetector(
              onTap: () {
                setState(() {
                  buttonClickValue = _inputController.text;
                });
              },
              child: Container(
                padding: EdgeInsets.all(10.0),
                margin: EdgeInsets.symmetric(vertical: 10.0),
                child: Text('按鈕'),
                decoration: BoxDecoration(color: Colors.blue),
              )),
          Text('onChange後:${onChangeValue}'),
          Text('onSubmit後:${onSubmitValue}'),
          Text('按下按鈕後:${buttonClickValue}'),
        ],
      )),
    ));
  }
}
呈現效果https://github.com/fenturechance/flutterPractice2021/tree/c459635a57411cadf53d8bb6463510a21a6c5ff1

沒有留言:

張貼留言