在 flutter 中使用资产图像作为选项卡图标

Using asset image as Tab icons in flutter

我想在 flutter 中从我的 TabBar 资产中加载图像。我的资产文件夹中有活动和非活动图像。图像渲染不佳,但我没有收到任何错误。

它们只是显示为矩形深色图像。我做错了什么?

import 'package:flutter/material.dart';

class Choice {
  final String title;
  final String image;

  Choice(this.title, this.image);
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<Choice> tabs = [
      Choice('Active', 'images/active.png'),
      Choice('Inactive', 'images/inactive.png'),
    ];

    return MaterialApp(
      home: DefaultTabController(
        length: tabs.length,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: tabs
                  .map((Choice tab) => Tab(
                text: tab.title,
                icon: Image.asset(tab.image),
              ))
                  .toList(),
            ),
          ),
        ),
      ),
    );
  }
}

Main.dart

  TabBar(
                      isScrollable: true,
                      tabs: choices.map<Widget>((Choice choice) {
                        return new Tab(icon: new Image.asset(choice.image), text: choice.title);
                      }).toList(),
                      labelColor: Color(0xFF1C2447),
                    )

对于您描述的用例,您不应使用 ImageIcon,您可以使用 Image.asset 提供程序让图像显示在您的选项卡中。

例如:

new Tab(icon: new Image.asset(choice.icon.image), text: choice.title),

下面是它的完整示例:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class Choice {
  final String title;
  final String image;

  Choice(this.title, this.image);
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<Choice> tabs = [
      Choice('Active', 'images/active.png'),
      Choice('Inactive', 'images/inactive.png'),
    ];

    return MaterialApp(
      home: DefaultTabController(
        length: tabs.length,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: tabs
                  .map((Choice tab) => Tab(
                        text: tab.title,
                        icon: Image.asset(tab.image),
                      ))
                  .toList(),
            ),
          ),
        ),
      ),
    );
  }
}