flutter实现ImageButton

82 阅读1分钟

定义ImageButton

import 'package:flutter/material.dart';

typedef ImgBtnFunc = void Function(String);

class ImageButton extends StatelessWidget {
  double width;
  double height;
  double iconSize;
  Color iconColor;

  String assetPath;
  String text;

  TextStyle textStyle;
  ImgBtnFunc func;

  ImageButton(this.assetPath,
      { this.width, this.height, this.iconSize, this.text, this.textStyle ,this.func });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => func(text),
      child: SizedBox(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(
              image: AssetImage(assetPath),
              width: this.iconSize,
              height: this.iconSize,
              fit: BoxFit.cover,
            ),
            Padding(
              padding: const EdgeInsets.only(top: 4),
              child: Text(text, style: textStyle),
            )
          ]
        ),
      ),
    );
  }
}

使用ImageButton

/// ICON列表
List<String> title = <String>["测试助手"];
List<String> path = <String>[
  "assets/images/header/head_menu_1.png",
];
/// 生成一行网格菜单
List<Widget> imageBtns = List<Widget>();
for (int i = 0; i < title.length; i++) {
  imageBtns.add(ImageButton(path[i],
      text: title[i], func: navigateTo, iconSize: 48,
      textStyle: TextStyle(color: AppColor.COMMON_666, fontSize: 13.0)
  ));
}
/// ICON列表
List<Map<String, String>> imageList = [
  { 'title': '测试助手', 'path': 'assets/images/header/head_menu_1.png' },
];
_generateButton(Map<String, String> json) {
  return ImageButton(json['path'], text: json['title'], func: navigateTo, iconSize: 48,
      textStyle: TextStyle(color: AppColor.COMMON_666, fontSize: 13.0));
}
List<Widget> imageBtnList = imageList.map((e) => _generateButton(e)).toList();