:::

6-13 父 Widget管理子 Widget的狀態

父 Widget

class _MyHomePageState extends State<MyHomePage> {
  String displayCate = '蔬菜類';

  // 改變狀態中分類的值
  void setDisplayCate(value) {
    setState(() {
      displayCate = value;
      print('displayCate:$displayCate');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FoodCateList(
        changeCate: setDisplayCate,
      ),
    );
  }
}

子 Widget

class FoodCateList extends StatelessWidget {
  final ValueChanged<String> changeCate;

  FoodCateList({ @required this.changeCate, Key key}):
        assert(changeCate != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemBuilder: (context, index) {
        FoodCate foodCate = snap.data[index];
        return FoodKindButton(
          changeCate: changeCate,
        );
      },
      separatorBuilder: (context, index) {},
      itemCount: snap.data.length
    ),
  }
}

底下某個按鈕

//單一個類別按鈕
class FoodKindButton extends StatelessWidget {
  final ValueChanged<String> changeCate;

  FoodKindButton(
      {@required this.changeCate, Key key})
        assert(changeCate != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return UnicornOutlineButton(
      onPressed: () {
        changeCate(title);
        return changeCate;
      },
    );
  }
}

 


:::

書籍目錄

展開 | 闔起

快速登入


http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1902%26tbsn%3D42

計數器

今天: 697697697
昨天: 3068306830683068
總計: 8077202807720280772028077202807720280772028077202