Flutter組件大全(四)

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,
            )
         ],
       );
   }
 }
複製代碼

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('請輸入正確的手機號');
     }
   }
 }
複製代碼

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'),
          )
         ],
       );
   }
   
 }

複製代碼

4.Column Row

垂直佈局組件和水平佈局組件api

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
              )
            ],
          )
         ],
       );
   }
   
 }

複製代碼

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
              )
            ],
           )
         ],
       );
   }
   
 }

複製代碼

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)
        )
      );
   }
   
 }
複製代碼

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),
                    )
                  ],
                )
              )
            ]
      );
   }
   
 }

複製代碼

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(),
                  ),
                )
              
              
            ]
      );
   }
   
 }

複製代碼

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('結束會議'),
                      )
                    )
                  ],
                )
              )
              
            ]
      );
   }
   
 }

複製代碼

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);
                }
              ),
            ]
      );
   }
   
 }

複製代碼

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,
              )
            ]
      );
   }
   
 }
複製代碼

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;
                   });
                 }
                )
            ]
      );
   }
   
 }

複製代碼

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,
                ),
               
            ]
      );
   }
   
 }

複製代碼

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);
              }
            );
          }
        ),
      ),
    );
  }
}
複製代碼

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('這是第三頁')
                  ),
                )
              ],
            ),
      );
   }
   
 }
複製代碼

相關文章
相關標籤/搜索