Flutter元件大全(四)

HTML小白發表於2020-06-01

1.Image

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
   @override 
   Widget build(BuildContext context) {
       return Column(
         children: <Widget>[
           Image.network(
             'https://dss2.bdstatic.com/8_V1bjqh_Q23odCf/pacific/1916399879.png',
            //  縮放係數
             scale: 2,
            )
         ],
       );
   }
 }
複製程式碼

Flutter元件大全(四)

2.TextField

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController password2Controller = TextEditingController();

   @override 
   Widget build(BuildContext context) {
       return Column(
         children: <Widget>[
           TextField(
             controller: usernameController,
            //  每個單詞的首字母大寫
            //  textCapitalization: TextCapitalization.words
            textCapitalization: TextCapitalization.none,
            // 輸入的鍵盤型別
            keyboardType: TextInputType.number,
            // 樣式
            decoration: InputDecoration(
              // 內邊框
              contentPadding: EdgeInsets.all(10.0),
              icon: Icon(Icons.person),
              // 提示文字
              labelText: '請輸入你的使用者名稱',
              helperText: '請輸入註冊的使用者名稱'
            ),
            // 游標顏色
            cursorColor: Colors.green,
            // 游標樣式
            cursorRadius: Radius.circular(16.0),
            // 游標大小
            cursorWidth: 16.0,
            // 完成按鈕
            textInputAction: TextInputAction.go,
           ),
           TextField(
             controller: passwordController,
             decoration: InputDecoration(
              //  外邊框
               border: OutlineInputBorder(),
               helperText: '請輸入使用者名稱',
               labelText: '使用者名稱',
               prefixIcon: Icon(Icons.person),
              //  右側圖示
              suffixIcon: Icon(Icons.print)
             )
           ),
           TextField(
             controller: password2Controller,
             keyboardType: TextInputType.number,
             decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.lock),
                labelText: '請輸入密碼'
             ),
            //  是否是安全的
             obscureText: true,
           ),
           RaisedButton(
             onPressed: (){
                loginCheck();
              },
              child: Text('登陸'),
           )
         ],
       );
   }
   loginCheck(){
     if(usernameController.text.length != 11){
       print('請輸入正確的手機號');
     }
   }
 }
複製程式碼

Flutter元件大全(四)

3.Container

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

   @override 
   Widget build(BuildContext context) {
       return Column(
         children: <Widget>[
          Container(
            width: 100.0,
            height: 100.0,
            decoration: BoxDecoration(
              color: Colors.greenAccent,
              border: Border.all(
                color: Colors.grey,
                width: 10.0,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(10.0)
              )
            ),
            child: Text('data'),
          )
         ],
       );
   }
   
 }

複製程式碼

Flutter元件大全(四)

4.Column Row

垂直佈局元件和水平佈局元件

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

   @override 
   Widget build(BuildContext context) {
       return Column(
         children: <Widget>[
          Column(
            // 主軸
            mainAxisAlignment: MainAxisAlignment.center,
            // 側軸
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                color: Colors.greenAccent,
                width: 100.0,
                height: 100.0
              )
            ],
          )
         ],
       );
   }
   
 }

複製程式碼

Flutter元件大全(四)

5.Conter 居中元件

6.ListBody

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

   @override 
   Widget build(BuildContext context) {
       return Column(
         children: <Widget>[
          //  ListBody 可以和 Column Row ListView 結合使用
           ListBody(
            //  對齊方式
             mainAxis: Axis.vertical,
            // 內容是否反向
            reverse: false,
            children: [
              Container(
                color: Colors.red,
                width: 30.0,
                height: 150.0
              ),
              Container(
                color: Colors.blue,
                width: 50.0,
                height: 150.0
              ),
              Container(
                color: Colors.yellow,
                width: 80.0,
                height: 150.0
              )
            ],
           )
         ],
       );
   }
   
 }

複製程式碼

Flutter元件大全(四)

7.ListView

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

   @override 
   Widget build(BuildContext context) {
      //  return  ListView(
      //       children: <Widget>[
      //         // 列表項
      //         ListTile(
      //           leading: Icon(Icons.ac_unit),
      //           title: Text('1'),
      //         ),
      //       //  分割線
      //         Divider(),
      //         ListTile(
      //           leading: Icon(Icons.ac_unit),
      //           title: Text('2'),
      //         ),
      //         ListTile(
      //           leading: Icon(Icons.ac_unit),
      //           title: Text('3'),
      //         ),
      //         ListTile(
      //           leading: Icon(Icons.ac_unit),
      //           title: Text('4'),
      //         )
      //       ]
          
      //  );
    //  return SizedBox(
    //     height: 300.0,

    //     child: ListView.builder(
    //         // 排列方向
    //         scrollDirection: Axis.vertical,
    //         // 列表項個數
    //         itemCount: 10,
    //         // 指定高度 可以提高效能
    //         itemExtent: 50.0,
    //         // 滑動型別
    //         physics: AlwaysScrollableScrollPhysics(),
    //         // 已載入區域
    //         cacheExtent: 30.0,
    //         // 滑動監聽
    //         controller: ScrollController(),
    //         // 如果未true 則不能滑動監聽
    //         primary: false,
    //         // 高度是否固定
    //         shrinkWrap: false,
    //         itemBuilder: (BuildContext context,int index){
    //           return ListTile(
    //             title: Text('$index'),
    //             leading: Icon(Icons.apps), // 前製圖示
    //             subtitle: Text('子標題$index'),
    //             // 後置圖示
    //             trailing: Icon(Icons.arrow_forward),
    //             // 是否顯示三行
    //             isThreeLine: false,
    //             contentPadding: EdgeInsets.all(10.0),
    //             // 是否可以
    //             enabled: true,
    //             // 點選事件
    //             onTap: (){},
    //             // 長按
    //             onLongPress: (){},
    //             // 是否選中
    //             selected: false,
    //           );
    //         }
    //       )
    //   );
      //    return SizedBox(
      //   height: 300.0,

      //   child: ListView.separated(
      //       // 排列方向
      //       scrollDirection: Axis.vertical,
      //       // 列表項個數
      //       itemCount: 100,
      //       // 分割線(必須)
      //       separatorBuilder: (BuildContext context, int index) => Divider() ,
      //       itemBuilder: (BuildContext context,int index){
      //         return ListTile(
      //           title: Text('$index'),
      //           leading: Icon(Icons.apps), // 前製圖示
      //           subtitle: Text('子標題$index'),
      //           // 後置圖示
      //           trailing: Icon(Icons.arrow_forward),
      //           // 是否顯示三行
      //           isThreeLine: false,
      //           contentPadding: EdgeInsets.all(10.0),
      //           // 是否可以
      //           enabled: true,
      //           // 點選事件
      //           onTap: (){},
      //           // 長按
      //           onLongPress: (){},
      //           // 是否選中
      //           selected: false,
      //         );
      //       }
      //     )
      // );
      // 自定義列表
      return SizedBox(
        height: 300.0,
        child: ListView.custom(
          scrollDirection: Axis.vertical,
          childrenDelegate: SliverChildBuilderDelegate((BuildContext context, int index){
            return Container(
              height: 50.0,
              alignment: Alignment.center,
              color: Colors.lightBlue[100 * (index % 9)],
              child: Text('$index'),
            );
          },childCount: 10)
        )
      );
   }
   
 }
複製程式碼

Flutter元件大全(四)

Flutter元件大全(四)

Flutter元件大全(四)

Flutter元件大全(四)

8.PopupMenuButton

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  // 已選擇選單項
  List<String> _checkedValues;

  final String _checkedValue1 = 'One';
  final String _checkedValue2 = 'Two';
  final String _checkedValue3 = 'Three';
  final String _checkedValue4 = 'Four';

  @override
  void initState(){
    super.initState();
    // 初始化已選擇選項
    _checkedValues = <String>[_checkedValue2];
  }

/*
 *fluttertoas彈出提示資訊 
 * fluttertoas.showToast(
 *  msg: value,
 *  toastLength: Toast.LENGTH_SHORT
 *  backgroundColor: Colors.grey
 *  textColor: Colors.white
 * )
 * 
 * **/ 
  // 檢測傳入的值 是否在_checkedValues裡
  bool isCheched(String value) => _checkedValues.contains(value);

  void showCheckedMenuSelections(String value){
    if(_checkedValues.contains(value)){
      _checkedValues.remove(value);
    }else{
      _checkedValues.add(value);
    }

    // showInSnackBar('Checked $__checkedValues');
  }

   @override 
   Widget build(BuildContext context) {
       return  ListView(
            children: <Widget>[
              ListTile(
                title: Text('選擇標記的彈出選單'),
                trailing: PopupMenuButton<String>(
                  padding: EdgeInsets.zero,
                  onSelected: showCheckedMenuSelections,
                  icon: Icon(Icons.menu),
                  itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                    // 有選擇標記的彈出選單
                    CheckedPopupMenuItem<String>(
                      // 當前項是否選中
                      enabled: true,
                      value: _checkedValue1,
                      checked: isCheched(_checkedValue1),
                      child: Text(_checkedValue1),
                    ),
                     CheckedPopupMenuItem<String>(
                      value: _checkedValue2,
                      checked: isCheched(_checkedValue2),
                      child: Text(_checkedValue2),
                    ),
                     CheckedPopupMenuItem<String>(
                      value: _checkedValue3,
                      checked: isCheched(_checkedValue3),
                      child: Text(_checkedValue3),
                    ),
                     CheckedPopupMenuItem<String>(
                      value: _checkedValue4,
                      checked: isCheched(_checkedValue4),
                      child: Text(_checkedValue4),
                    )
                  ],
                )
              )
            ]
      );
   }
   
 }

複製程式碼

Flutter元件大全(四)

9.ListTile

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
 

  String dropdownValue = 'One';

   @override 
   Widget build(BuildContext context) {
       return  ListView(
            children: <Widget>[
              ListTile(
                title: Text('下拉選單'),
                trailing: DropdownButton(
                  value: dropdownValue,
                  onChanged: (String val){
                    setState(() {
                      dropdownValue  = val;
                    });
                  },
                  items: <String>['One',"Two","Three"].map<DropdownMenuItem<String>>((String val){
                    // 渲染每一個可選項
                    return DropdownMenuItem<String>(
                      value: val,
                      child: Text(val),
                    );
                  }).toList(),
                  ),
                )
              
              
            ]
      );
   }
   
 }

複製程式碼

Flutter元件大全(四)

10.PopupMenuButton

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

  void printSelectValue(String val){
    print(val);
  }

   @override 
   Widget build(BuildContext context) {
       return  ListView(
            children: <Widget>[
              ListTile(
                title: Text('彈出選單'),
                trailing: PopupMenuButton<String>(
                  padding: EdgeInsets.zero,
                  onSelected: printSelectValue,
                  itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                    // 選單項
                    PopupMenuItem(
                      value: '會議',
                      child: ListTile(
                        leading: Icon(Icons.lock),
                        title: Text('鎖定會議'),
                      )
                    ),
                    // 分割線
                    PopupMenuDivider(),
                    PopupMenuItem(
                      value: '結束會議',
                      child: ListTile(
                        leading: Icon(Icons.lock),
                        title: Text('結束會議'),
                      )
                    )
                  ],
                )
              )
              
            ]
      );
   }
   
 }

複製程式碼

Flutter元件大全(四)

11.日期元件

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

  DateTime _date = new DateTime.now();
  TimeOfDay _time = new TimeOfDay.now();

  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
      context: context, 
      // 初始化日期
      initialDate: new DateTime.now(),
      // 起始日期
      firstDate: DateTime(2019,1), 
      // 結束日期
      lastDate: DateTime(2020),
      
    );
    if (picked != null && picked != _date) {
        print('當前選擇的日期是: ${_date.toString()}');
      }

    if(picked == null){
      _date = new DateTime.now();
    }
    setState(() {
      _date = picked;
    });
  }

  Future<void> _selectTime(BuildContext context) async {
    final TimeOfDay picked = await showTimePicker(
      context: context, 
      // 初始化時間
        initialTime: _time,
      // 起始時間
      // firstDate: DateTime(2019,1), 
      // 結束時間
      // lastDate: DateTime(2020),
      
    );
    if (picked != null && picked != _time) {
        print('當前選擇的日期是: ${_date.toString()}');
      }

    if(picked == null){
      _time = new TimeOfDay.now();
    }
    setState(() {
      _time = picked;
    });
  }


   @override 
   Widget build(BuildContext context) {
       return  ListView(
            children: <Widget>[
              Text('日期選擇'),
              RaisedButton(
                child: Text('日期選擇'),
                onPressed: (){
                  _selectDate(context);
                }
              ),
              Text('時間選擇'),
              RaisedButton(
                child: Text('時間選擇'),
                onPressed: (){
                  _selectTime(context);
                }
              ),
            ]
      );
   }
   
 }

複製程式碼

Flutter元件大全(四)

12.進度條

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {



   @override 
   Widget build(BuildContext context) {
       return  ListView(
            children: <Widget>[
              CircularProgressIndicator(),
              SizedBox(
                height: 100.0
              ),
              LinearProgressIndicator(
                backgroundColor: Colors.red,
                valueColor: AlwaysStoppedAnimation(Colors.yellow),
                value: 0.3,
              )
            ]
      );
   }
   
 }
複製程式碼

Flutter元件大全(四)

13.單選

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

  int groupValue = 1;

   @override 
   Widget build(BuildContext context) {
       return  ListView(
            children: <Widget>[
               Radio(
                //  選中顏色
                 activeColor: Colors.red,
                //  值
                 value: 1, 
                //  當groupValue 和 value 一致是選中
                 groupValue: groupValue, 
                 onChanged: (T){
                   setState(() {
                     groupValue = T;
                   });
                 }
                ),
                Radio(
                //  值
                 value: 3, 
                //  當groupValue 和 value 一致是選中
                 groupValue: groupValue, 
                 onChanged: (T){
                   setState(() {
                     groupValue = T;
                   });
                 }
                ),
                Radio(
                //  值
                 value: 2, 
                //  當groupValue 和 value 一致是選中
                 groupValue: groupValue, 
                 onChanged: (T){
                   setState(() {
                     groupValue = T;
                   });
                 }
                )
            ]
      );
   }
   
 }

複製程式碼

Flutter元件大全(四)

14.帶文字的單選

class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {

  int groupValue = 1;

  onChange(v){
    this.setState(() {
      groupValue = v;
    });
  }

   @override 
   Widget build(BuildContext context) {
       return  ListView(
            children: <Widget>[
               RadioListTile(
                //  選中顏色
                 activeColor: Colors.red,
                  title: Text('星期一'),
                  value: 1,
                  // 右側圖示
                  secondary: Icon(Icons.lock),
                  groupValue: this.groupValue,
                  isThreeLine: false,
                  subtitle: Text('子標題'),
                  onChanged: onChange,
                ),
               
            ]
      );
   }
   
 }

複製程式碼

Flutter元件大全(四)

15.Scaffold


class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
     
      home: Scaffold(
        appBar: AppBar(
          title: Text('Icon元件'),
          backgroundColor: Colors.red,
          // 標題居中
          centerTitle: true,
          // 陰影
          elevation: 10.0,
          // 左側圖示
          leading: Icon(Icons.home),
          actions: [
            Icon(Icons.add)
          ],
          bottom: PreferredSize(
            child: Container(
              height: 50.0,
              child: Center(
                child: Text('顯示在標題下面的內容'),
              ),
              decoration: BoxDecoration(
                color: Colors.redAccent
              ),
            ), 
            preferredSize: Size.fromHeight(50.0)
          ),
        ),
        body: Container(
          child: DemoPage()
          
        ),
        // 左側邊欄
        drawer: Drawer(
          child: Container(
            width: 150.0,
            color: Colors.orange,
            child: Text('側邊欄')
          ),
        ),
        // 底部持久化按鈕
        persistentFooterButtons: [
          Icon(Icons.home),
          Icon(Icons.home),
          Icon(Icons.home),
          Icon(Icons.home),
          Icon(Icons.home)
        ],
        // 底部導航(帶文字的)
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: 1,
          fixedColor: Colors.redAccent,
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('主頁')
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('聊天')
            )
          ]
        ),

        floatingActionButton: Builder(
          builder: (BuildContext context){
            return FloatingActionButton(
              backgroundColor: Colors.redAccent,
              child: Icon(Icons.add),
              onPressed: (){
                var snackbar = SnackBar(
                  content: Text('顯示SnackBar'),
                  backgroundColor: Colors.red,
                  duration: Duration(
                    milliseconds: 500
                  ),
                  action: SnackBarAction(
                    label: "撤銷",
                    onPressed: (){}
                  ),
                );
                Scaffold.of(context).showSnackBar(snackbar);
              }
            );
          }
        ),
      ),
    );
  }
}
複製程式碼

Flutter元件大全(四)

16.整頁切換


class DemoPage extends StatefulWidget {
  @override 
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {


   @override 
   Widget build(BuildContext context) {
       return  Container(
            height: 400.0,
            child: PageView(
              // 翻滾方向
              scrollDirection: Axis.vertical,
              children: [
                Container(
                  color : Colors.redAccent,
                  child: Center(
                    child: Text('這是第一頁')
                  ),
                ),
                Container(
                  color : Colors.redAccent,
                  child: Center(
                    child: Text('這是第二頁')
                  ),
                ),
                Container(
                  color : Colors.redAccent,
                  child: Center(
                    child: Text('這是第三頁')
                  ),
                )
              ],
            ),
      );
   }
   
 }
複製程式碼

Flutter元件大全(四)

相關文章