Как использовать значок .svg из локального в flutter?

#flutter #dart #svg #icons

#flutter #dart #svg #Значки

Вопрос:

Я пытаюсь показать значок svg, который я добавил в папку своего проекта assets/contact/tag.svg и определил его путь в pubspec.yaml. но получение исключения

 Picture key: AssetBundlePictureKey(bundle: PlatformAssetBundle#aeb88(), name:
I/flutter (10891):   "assets/contact/tag.svg", colorFilter: null)
 

Я использовал плагин flutter_svg для отображения значка svg

код:

 class ProfileAboutMe extends StatelessWidget {
  const ProfileAboutMe({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
       body: Container(
         alignment: Alignment.center,
        padding: EdgeInsets.only(
          left: 24,
          top: 14,
          right: 24,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'ABOUT ME',
                  overflow: TextOverflow.fade,
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                    color: Color(0xff4e4b6f),
                  ),
                ),
               SvgPicture.asset(
                'assets/contact/tag.svg',
                height: 40,
                width: 40,
                ),

                // IconButton(
                //     onPressed: () => print('abc'),
                //     icon: Icon(Icons.edit_outlined)),
              ],
            ),
            SizedBox(
              height: 10,
            ),
            RichText(
              text: TextSpan(
                style: TextStyle(
                  color: Color(0xff4e4b6f),
                ),
                children: <TextSpan>[
                  TextSpan(
                    text:
                        "Hey guys, This is Anna. I'm here to find someone for hookup. I'm not interested in something serious. I would love to hear your adventurous story",
                    style: TextStyle(
                      fontSize: 15,
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
 

вместо значка отображается черный контейнер:

введите описание изображения здесь

Скриншот моего значка svg: введите описание изображения здесь

мое сообщение в журнале:

 
Syncing files to device Redmi 8A...                              1,240ms

Flutter run key commands.
r Hot reload. 🔥🔥🔥
R Hot restart.
h Repeat this help message.
d Detach (terminate "flutter run" but leave application running).
c Clear the screen
q Quit (terminate the application on the device).
An Observatory debugger and profiler on Redmi 8A is available at: http://127.0.0.1:60801/fltQBNjDVcA=/
W/Gralloc3( 8654): mapper 3.x is not supported
I/OpenGLRenderer( 8654): Davey! duration=3648ms; Flags=1, IntendedVsync=216833028460600, Vsync=216833211793926, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=216833215017697, AnimationStart=216833215155197, PerformTraversalsStart=216833215167020, DrawStart=216836489206393, SyncQueued=216836517323321, SyncStart=216836517942487, IssueDrawCommandsStart=216836518714206, SwapBuffers=216836674754727, FrameCompleted=216836677195925, DequeueBufferDuration=3498000, QueueBufferDuration=1371000, 
W/Looper  ( 8654): Slow Looper main: Long Msg: seq=10 plan=13:19:41.416  late=186ms wall=3464ms running=0ms h=android.view.Choreographer$FrameHandler c=android.view.Choreographer$FrameDisplayEventReceiver
I/Choreographer( 8654): Skipped 209 frames!  The application may be doing too much work on its main thread.
W/Looper  ( 8654): Slow Looper main: doFrame is 3499ms late because of 2 msg, msg 1 took 3464ms (seq=10 late=186ms h=android.view.Choreographer$FrameHandler c=android.view.Choreographer$FrameDisplayEventReceiver)
I/flutter ( 8654): ══╡ EXCEPTION CAUGHT BY SVG ╞═══════════════════════════════════════════════════════════════════════
I/flutter ( 8654): The following UnimplementedError was thrown in parseSvgElement:
I/flutter ( 8654): The <style> element is not implemented in this library.
I/flutter ( 8654): 
I/flutter ( 8654): Style elements are not supported by this library and the requested SVG may not render as intended.
I/flutter ( 8654): If possible, ensure the SVG uses inline styles and/or attributes (which are supported), or use a
I/flutter ( 8654): preprocessing utility such as svgcleaner to inline the styles for you.
I/flutter ( 8654): 
I/flutter ( 8654): Picture key: AssetBundlePictureKey(bundle: PlatformAssetBundle#107cd(), name:
I/flutter ( 8654):   "assets/discover/scan.svg", colorFilter: null)
I/flutter ( 8654): ════════════════════════════════════════════════════════════════════════════════════════════════════
 

Комментарии:

1. Попробуйте использовать свойство Color, иначе я думаю, что есть проблема с вашим svg-файлом, попробуйте с другим.

2. Я попробовал свойство color (color: Colors.red), но ничего не произошло, отображается красным.

3. Вы пробовали использовать другой значок svg?

4. Пожалуйста, попробуйте перезапустить свой эмулятор

5. @AR я пробовал, но тот же результат

Ответ №1:

Ваша проблема и решение четко указаны здесь:

 I/flutter ( 8654): The <style> element is not implemented in this library.
I/flutter ( 8654): Style elements are not supported by this library and the requested SVG may not render as intended.
I/flutter ( 8654): If possible, ensure the SVG uses inline styles and/or attributes (which are supported), or use a
I/flutter ( 8654): preprocessing utility such as svgcleaner to inline the styles for you.
 

Позвольте мне прояснить это для вас:

flutter_svg пакет не поддерживает svg состоит из internal css :

  <style>
       .....
  </style>
 

Итак, чтобы заставить его работать, вам нужно удалить internal css и записать inline css или использовать другое изображение svg или использовать утилиту предварительной обработки, такую как Svgcleaner, чтобы встроить стили для вас.

Вы можете загрузить Svgcleaner в свою ОС отсюда или по прямой ссылке для скачивания — исполняемый файл для ОС Windows.

Но я рекомендую вам лучше использовать другое svg изображение, которого нет internal css в его коде.

Комментарии:

1. Я попытался очистить файлы svg с помощью svgcleaner, на который вы ссылались здесь, но все равно получил ту же ошибку. Но затем я открыл очищенные файлы svg в vs code и увидел, что тег <style> все еще там. Я прокомментировал тег стиля и его содержимое. Теперь он не выдает никаких ошибок. Это нормально или с этим есть какие-то проблемы? Нужно ли мне делать что-то еще с тегом style?

Ответ №2:

вы можете попробовать использовать этот пакет https://pub.dev/packages/flutter_svg

Комментарии:

1. Внимательно прочитайте вопрос, прежде чем отвечать. Ваш ответ слишком короткий и не содержит никаких объяснений, поэтому его можно включить в раздел комментариев.