2019年10月2日 星期三

Flutter 透過高階函式(high orfer function)溝通 Widget

當參數帶有迴調函式時稱為高階函式,  StatefulWidget 與下層 Widget 溝通就可透過建構式傳遞高階函式方式當參數, 架起溝通管道, 底下 MyButton 雖然是一個 StatelessWidget 創造的 widget, 透過技巧可讓它看起來多彩多姿, 範例程式:
import 'package:flutter/material.dart';
void main() => runApp(MyApp( ));
class MyApp extends StatelessWidget {
  @override build(BuildContext context) => MaterialApp(
      theme : ThemeData.dark(),
      home  : MyHomePage()
  );
}
class MyHomePage extends StatefulWidget {
   @override  createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  final colors = <Color>[Colors.red, Colors.orange, Colors.yellow, Colors.green, Colors.blue, Colors.cyan,Colors.purple];
  String  title = '按下按鍵更改標題';
  int     index = 0;  // 顏色索引
  Color color( ) { // callback function to send color
    index = (index +1) % colors.length;
    return colors[index];
  }
  void changeTitle(String _) {  // callback function to change title
    setState( ( ) => title =_ ); // setState to rebuild Scaffold widget
  }
  @override build(BuildContext context) => Scaffold(
      appBar: AppBar(title: Center(child:Text(title))),
      body  : Center(child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[MyButton(color, changeTitle)],
      ))
  ); 
}
class MyButton extends StatelessWidget {
  final Color Function( ) colorIn;
  final void Function(String) titleOut;
  MyButton(this.colorIn, this.titleOut);
  @override build(BuildContext context) => FlatButton.icon(
      onPressed : ( ) => titleOut('這是新標題'),
      color     : colorIn(), // get color
      label     : Text('按下按鍵更改顏色'), 
      icon      : Icon(Icons.color_lens)
  ); 
}

沒有留言:

張貼留言

使用 linux 玩早期的 Turbo C

Turbo C  是早期在 dos (磁碟作業系統)底下的用來編譯 C 語言的編譯程式,可以上官網下載:              https://turbo-c.net/turbo-c-download/ 為了讓它能在 linux 底下順利運作, 可以安裝 dosbox:   ...