簡體   English   中英

如何在 Flutter 的 IconData 中插入變量?

[英]How to interpolate a variable in IconData in Flutter?

我想展示社交媒體的圖標。

String socialMedia = 'facebook'; 

然后在我的構建 function 我想在我的圖標小部件中使用這個變量

Icon(FontAwesomeIcons.socialMedia)

我怎樣才能插入這個變量? 可能嗎? 如果我可以像這樣使用變量,對我來說會變得很容易。 因為現在我可以使用變量來相應地更改圖標。

您可以在下面復制粘貼運行完整代碼
您可以使用 package https://pub.dev/packages/icons_helper
您可以使用getIconUsingPrefix ,對於FontAwesome Icon,您可以使用fa.

代碼片段

Icon(getIconUsingPrefix(name: 'fa.fiveHundredPx'),
                color: Theme.of(context).backgroundColor, size: 128.0),
Icon(getIconUsingPrefix(name: 'fa.facebook'),
    color: Theme.of(context).backgroundColor, size: 128.0),
Icon(getIconUsingPrefix(name: 'add'),
    color: Theme.of(context).backgroundColor, size: 128.0),

工作演示

在此處輸入圖像描述

完整代碼

import 'package:flutter/material.dart';
import 'package:icons_helper/icons_helper.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(       
        primarySwatch: Colors.blue,       
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {     
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {    
    return Scaffold(
      appBar: AppBar(       
        title: Text(widget.title),
      ),
      body: Center(        
        child: Column(          
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(getIconUsingPrefix(name: 'fa.fiveHundredPx'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Icon(getIconUsingPrefix(name: 'fa.facebook'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Icon(getIconUsingPrefix(name: 'add'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM