flutter demo (一):居中的按鈕

zty5678發表於2018-08-09

效果圖:

1.jpg

程式碼如下:

import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
  @override
  TestMyAppState createState() => new TestMyAppState();
}

class TestMyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    final key = new GlobalKey<ScaffoldState>();
    return new MaterialApp(
      home: new Scaffold(
        key: key,
        appBar: new AppBar(title: new Text("test app")),
        body: new Container(
            alignment: Alignment.center,
            child: new Container(
              child: new RaisedButton(
                padding: new EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0), //padding
                child: new Text(
                  'test',
                  style: new TextStyle(
                    fontSize: 18.0, //textsize
                    color: Colors.white,// textcolor
                  ),
                ),
                color: Theme.of(context).accentColor,
                elevation: 4.0,  //shadow
                splashColor: Colors.blueGrey, 
                onPressed: () {
                  //click event: show a snack bar
                  key.currentState.showSnackBar(new SnackBar(
                    content: new Text('Hello!'),
                  ));
                }
              ),
            )),
      ),
    );
  }
}

複製程式碼

目前flutter官方暫時未提供toast工具類,如果想彈出toast, 可以利用第三方庫fluttertoast:https://github.com/PonnamKarthik/FlutterToast 。 目前其作者提交到官方倉庫的最新版本是2.0.3: https://pub.dartlang.org/packages/fluttertoast 。

如何新增依賴? 找到專案中的 pubspec.yaml 檔案,

name: layouts_flutter
description: A new Flutter application.

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.0
  fluttertoast: ^2.0.3   #新增到這裡即可

dev_dependencies:
  flutter_test:
    sdk: flutter
...
複製程式碼

修改完點選右上角的"Packages get"即可。

顯示toast的程式碼:

Fluttertoast.showToast(
  msg: "This is Center Short Toast",
  toastLength: Toast.LENGTH_SHORT,
  gravity: ToastGravity.BOTTOM,
  timeInSecForIos: 1
);                    
複製程式碼

注意不要忘了新增import:

import 'package:fluttertoast/fluttertoast.dart';
複製程式碼

相關文章