Flutter基本使用

Flutter使用文檔

創(chuàng)建應(yīng)用主題

為了在整個應(yīng)用程序中共享包含顏色和字體樣式的主題,我們可以提供ThemeData給MaterialApp的構(gòu)造函數(shù)。

如果沒有提供theme,F(xiàn)lutter將創(chuàng)建一個默認(rèn)主題。

new MaterialApp(
  title: title,
  theme: new ThemeData(
    brightness: Brightness.dark,
    primaryColor: Colors.lightBlue[800],
    accentColor: Colors.cyan[600],
  ),
);

顯示圖片

顯示圖片是大多數(shù)移動應(yīng)用程序的基礎(chǔ)。Flutter提供了Image Widget來顯示不同類型的圖片。

//支持GIF動畫
new Image.network(
  'https://raw.githubusercontent.com/flutter/website/master/_includes/code/layout/lakes/images/lake.jpg',
)

FadeInImage適用于任何類型的圖片:內(nèi)存、本地Asset或來自網(wǎng)上的圖片。

new FadeInImage.memoryNetwork(
  placeholder: kTransparentImage,
  image: 'https://github.com/flutter/website/blob/master/_includes/code/layout/lakes/images/lake.jpg?raw=true',
);

緩存圖片,在從網(wǎng)上下載圖片后緩存圖片可能會很方便,以便它們可以脫機使用。

new CachedNetworkImage(
  placeholder: new CircularProgressIndicator(),
  imageUrl: 'https://github.com/flutter/website/blob/master/_includes/code/layout/lakes/images/lake.jpg?raw=true',
);

可以看到使用CachedNetworkImage同時也可以使用占位符,可以使用任何的Widget作為占位符!

ListView(短列表)

new ListView(
  children: <Widget>[
    new ListTile(
      leading: new Icon(Icons.map),
      title: new Text('Maps'),
    ),
    new ListTile(
      leading: new Icon(Icons.photo_album),
      title: new Text('Album'),
    ),
    new ListTile(
      leading: new Icon(Icons.phone),
      title: new Text('Phone'),
    ),
  ],
);

水平的ListView

new ListView(
  // This next line does the trick.
  scrollDirection: Axis.horizontal,
  children: <Widget>[
    new Container(
      width: 160.0,
      color: Colors.red,
    ),
    new Container(
      width: 160.0,
      color: Colors.blue,
    ),
    new Container(
      width: 160.0,
      color: Colors.green,
    ),
    new Container(
      width: 160.0,
      color: Colors.yellow,
    ),
    new Container(
      width: 160.0,
      color: Colors.orange,
    ),
  ],
)

只需要指定scrollDirection: Axis.horizontal即可,默認(rèn)當(dāng)然是垂直的。

ListView.builder(長列表)

處理包含大量數(shù)據(jù)的列表,最好使用ListView.builder構(gòu)造函數(shù)。ListView的構(gòu)造函數(shù)需要一次創(chuàng)建所有項目,但ListView.builder的構(gòu)造函數(shù)不需要,它將在列表項滾動到屏幕上時創(chuàng)建該列表項。

  1. 創(chuàng)建一個數(shù)據(jù)源final items = new List<String>.generate(10000, (i) => "Item $i");
  2. 將數(shù)據(jù)源轉(zhuǎn)化為Widgets
new ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    return new ListTile(
      title: new Text('${items[index]}'),
    );
  },
);

創(chuàng)建不同item的ListView.builder

大多數(shù)情況下,List Item并不是完全相同的。當(dāng)然Flutter也可以創(chuàng)建不同Item的ListView

  1. 首先創(chuàng)建不同的Item類型
// The base class for the different types of items the List can contain
abstract class ListItem {}

// A ListItem that contains data to display a heading
class HeadingItem implements ListItem {
  final String heading;

  HeadingItem(this.heading);
}

// A ListItem that contains data to display a message
class MessageItem implements ListItem {
  final String sender;
  final String body;

  MessageItem(this.sender, this.body);
}
  1. 創(chuàng)建Item列表
inal items = new List<ListItem>.generate(
  1200,
  (i) => i % 6 == 0
      ? new HeadingItem("Heading $i")
      : new MessageItem("Sender $i", "Message body $i"),
);
  1. 將數(shù)據(jù)源轉(zhuǎn)換為Widgets列表
new ListView.builder(
  // Let the ListView know how many items it needs to build
  itemCount: items.length,
  // Provide a builder function. This is where the magic happens! We'll
  // convert each item into a Widget based on the type of item it is.
  itemBuilder: (context, index) {
    final item = items[index];

    if (item is HeadingItem) {
      return new ListTile(
        title: new Text(
          item.heading,
          style: Theme.of(context).textTheme.headline,
        ),
      );
    } else if (item is MessageItem) {
      return new ListTile(
        title: new Text(item.sender),
        subtitle: new Text(item.body),
      );
    }
  },
);

點擊事件

在Flutter中GestureDetector Widget這個也屬于一個widget,手勢操作在Android中屬于一個事件。

創(chuàng)建一個自定義按鈕,當(dāng)點擊時顯示一個SnackBar。

// Our GestureDetector wraps our button
new GestureDetector(
  // When the child is tapped, show a snackbar 
  onTap: () {
    final snackBar = new SnackBar(content: new Text("Tap"));

    Scaffold.of(context).showSnackBar(snackBar);
  },
  // Our Custom Button!
  child: new Container(
    padding: new EdgeInsets.all(12.0),
    decoration: new BoxDecoration(
      color: Theme.of(context).buttonColor,
      borderRadius: new BorderRadius.circular(8.0),
    ),
    child: new Text('My Button'),
  ),
);

滑動手勢

滑動手勢也是一個Widget。

  1. 創(chuàng)建數(shù)據(jù)源
final items = new List<String>.generate(20, (i) => "Item ${i + 1}");
  1. Dismissible Widget(滑動item)
new Dismissible(
  // Each Dismissible must contain a Key. Keys allow Flutter to
  // uniquely identify Widgets.
  key: new Key(item),
  // We also need to provide a function that will tell our app
  // what to do after an item has been swiped away.
  onDismissed: (direction) {
    // Remove the item from our data source
    items.removeAt(index);

    // Show a snackbar! This snackbar could also contain "Undo" actions.
    Scaffold.of(context).showSnackBar(
        new SnackBar(content: new Text("$item dismissed")));
  },
  child: new ListTile(title: new Text('$item')),
);
  1. ListView.builder創(chuàng)建item
new ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];

            return new Dismissible(
              // Each Dismissible must contain a Key. Keys allow Flutter to
              // uniquely identify Widgets.
              key: new Key(item),
              // We also need to provide a function that will tell our app
              // what to do after an item has been swiped away.
              onDismissed: (direction) {
                items.removeAt(index);

                Scaffold.of(context).showSnackBar(
                    new SnackBar(content: new Text("$item dismissed")));
              },
              // Show a red background as the item is swiped away
              background: new Container(color: Colors.red),
              child: new ListTile(title: new Text('$item')),
            );

Navigator

創(chuàng)建兩個頁面

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('First Screen'),
      ),
      body: new Center(
        child: new RaisedButton(
          child: new Text('Launch new screen'),
          onPressed: () {
            Navigator.push(
              context,
              new MaterialPageRoute(builder: (context) => new SecondScreen()),
            );
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Second Screen"),
      ),
      body: new Center(
        child: new RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: new Text('Go back!'),
        ),
      ),
    );
  }
}

點擊跳轉(zhuǎn)到下一個頁面

onPressed: () {
  Navigator.push(
    context,
    new MaterialPageRoute(builder: (context) => new SecondScreen()),
  );
}

調(diào)用Navigator.pop返回第一個頁面

onPressed: () {
  Navigator.pop(context);
}

Widget傳值

  1. 創(chuàng)建model
class Todo {
  final String title;
  final String description;

  Todo(this.title, this.description);
}
  1. 創(chuàng)建一個model List集合
final todos = new List<Todo>.generate(
  20,
  (i) => new Todo(
        'Todo $i',
        'A description of what needs to be done for Todo $i',
      ),
);
  1. 用一個ListView.builder將點擊對應(yīng)item的數(shù)據(jù)傳到詳情界面
new ListView.builder(
  itemCount: todos.length,
  itemBuilder: (context, index) {
    return new ListTile(
      title: new Text(todos[index].title),
      // When a user taps on the ListTile, navigate to the DetailScreen.
      // Notice that we're not only creating a new DetailScreen, we're
      // also passing the current todo to it!
      onTap: () {
        Navigator.push(
          context,
          new MaterialPageRoute(
            builder: (context) => new DetailScreen(todo: todos[index]),
          ),
        );
      },
    );
  },
);
  1. 在Detail頁面接收數(shù)據(jù)
class DetailScreen extends StatelessWidget {
  // Declare a field that holds the Todo
  final Todo todo;

  // In the constructor, require a Todo
  DetailScreen({Key key, @required this.todo}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // Use the Todo to create our UI
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("${todo.title}"),
      ),
      body: new Padding(
        padding: new EdgeInsets.all(16.0),
        child: new Text('${todo.description}'),
      ),
    );
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 在 上一篇文章 中,我們講解了 Flutter 開發(fā)環(huán)境搭建 , 以及運行了官方demo簡單體驗了下 Flutte...
    Lmaoshammy閱讀 2,303評論 6 4
  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,552評論 0 17
  • 知行合一 兩日前,突如其來的興致或說決心,留下段現(xiàn)在看來不甚有味道的文字。不過倒能多少記錄當(dāng)時的心情。 文字寫下次...
    3e7598d49cbc閱讀 260評論 0 0
  • 你似人間仙子 美麗魅力 你的文字 歷經(jīng)世事變遷 依然撼動著無數(shù)人 你無數(shù)經(jīng)典 至今讓人仰慕 你許多愛情箴言 現(xiàn)世照...
    飯廳閱讀 537評論 0 1
  • 想到許老師布置的作業(yè),我真是頭疼,我自己有什么好介紹的呢,我不擅長寫東西,更不擅長寫自己,自己最是無趣的一...
    史云芬閱讀 262評論 2 5