How to add SVGs to AppBar class in Flutter? - flutter

I'd like to be able to add an svg image to the AppBar in my flutter application. I've used a package called flutter_svg to add the svgs to the project, however the images do not appear in the project. The code in the main is as follows:
class FrontpageState extends State<Frontpage> {
//mother widget
Widget build(BuildContext context) {
final Widget svgJuro = SvgPicture.asset(juro);
final Widget svgBanco = SvgPicture.asset(banco, semanticsLabel: 'Banco');
final Widget svgGoverno =
SvgPicture.asset(titulos, semanticsLabel: 'Titulos');
final Widget svgFundos = SvgPicture.asset(fundos, semanticsLabel: 'Fundos');
final Widget svgQuestao =
SvgPicture.asset(questao, semanticsLabel: 'Questão');
return Scaffold(
appBar: AppBar(
shadowColor: jBrown100,
title: Align(
alignment: Alignment(-0.6, 0),
child: Text('JURAS?',
style: GoogleFonts.roboto(
color: jBlack100,
fontSize: 48,
fontWeight: FontWeight.w700,
letterSpacing: -2))),
actions: [
new IconButton(icon: svgJuro, onPressed: null, color: jPink100)
],
));
}
The code in the dependencies and a separate assets dart file:
dependencies:
flutter:
sdk: flutter
google_fonts: ^1.1.1
flutter_svg: ^0.19.1
//assets.dart
final String juro = 'imgAsset/juro.svg';
final String banco = 'imgAsset/banco.svg';
final String titulos = 'imgAsset/governo.svg';
final String fundos = 'imgAsset/fundos.svg';
final String questao = 'imgAsset/questao.svg';
I put the SVG in the actions because I want to animate the SVG in the future. I think the only way I can achieve this is through a custom appbar using a container, here is the design I am trying to implement, please give me any suggestions regarding making this design a reality:
Thank you in advance for your help.

Just make sure that your images are .svg format [use a convertor to convert to .svg format]. I had a similar issue as the one mentioned when trying to display a .png image.

1.Enable Custom assets. Then move your svg file to assets folder.
2.Run this command:
With Flutter:
$ flutter pub add flutter_svg
3.Now in your Dart code, you can use:
import 'package:flutter_svg/flutter_svg.dart';
4.Code Like This:
title: SvgPicture.asset('./assets/traveler.svg'),

Related

I placed icons created with the "Flutter custom icons generator". But something is wrong.I would like to set up icons with a SVG-like design

issue
I want to put icons like SVG.
But I can't put it.
The dart file generated by the Flutter custom icons generator.
class WDLogo {
WDLogo._();
static const _kFontFam = 'WDLogo';
static const String? _kFontPkg = null;
static const IconData arrow_back = IconData(0xe801, fontFamily: _kFontFam, fontPackage: _kFontPkg);
static const IconData arrow_forward = IconData(0xe802, fontFamily: _kFontFam, fontPackage: _kFontPkg);
static const IconData menu = IconData(0xe803, fontFamily: _kFontFam, fontPackage: _kFontPkg);
}
pubspec.yaml
fonts:
- family: WDLogo
fonts:
- asset: assets/fonts/WDLogo.ttf
icon widget
"Icon(WDLogo.arrow_back))"
https://www.fluttericon.com/
SVG (Correct icon)
Mac folder
Flutter custom icons generator
Mac font preview
You need to add your fonts to asset folder and defined it on pubspec.yaml file like this
flutter:
fonts:
- family: MyFlutterApp
fonts:
- asset: fonts/MyFlutterApp.ttf
first add plugin ,link : https://pub.dev/packages/fluttericon/install
to your pubsepec.yaml file. after that import file.
then
Call Your icons like this
final myIcons = const <Widget>[
const Icon(Typicons.attention),
const Icon(Fontelico.emo_wink),
const Icon(Linecons.globe),
];
DONT USE LIKE THIS "Icon(WDLogo.arrow_back))",
if You need to use SVG , you can use this Flutter svg plugin for that ,
link for plugin https://pub.dev/packages/flutter_svg
final String assetName = 'assets/image.svg';
final Widget svg = SvgPicture.asset(
assetName,
semanticsLabel: 'Acme Logo'
);

Flutter cant load image from url

════════ Exception caught by image resource service ════════════════════════════
The following ImageCodecException was thrown resolving an image codec:
Failed to load network image.
Image URL: https://cdn.sportmonks.com/images/soccer/leagues/5.png
Trying to load an image from another domain? Find answers at:
https://flutter.dev/docs/development/platform-integration/web-images
When i try the demo URL https://picsum.photos/250?image=9 it is working but the url above is good so what can be the problem?
class ListRow extends StatelessWidget {
final String name;
final imageUrl;
const ListRow({Key key, this.name, this.imageUrl}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
width: 18,
height: 18,
child: Image(
image: NetworkImage(
'https://cdn.sportmonks.com/images/soccer/leagues/5.png'),
),
),
SizedBox(width: 10),
Flexible(
child: new Text(
name,
style:
new TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
),
),
],
);
}
}
So flutter web has upgraded default rendered(HTML) -> CanvasKit and it has better performance.
You are most likely getting this error because CORS(can check chrome network tab to be sure).
To solve it could:
Update cors settings server side: https://stackoverflow.com/a/66104543/4679965
Run app with old rendered:
flutter run -d chrome --web-renderer html // to run the app
flutter build web --web-renderer html --release // to generate a production build
Or display images with platform view:
import 'dart:html';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
class MyImage extends StatelessWidget {
#override
Widget build(BuildContext context) {
String imageUrl = "image_url";
// https://github.com/flutter/flutter/issues/41563
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
imageUrl,
(int _) => ImageElement()..src = imageUrl,
);
return HtmlElementView(
viewType: imageUrl,
);
}
}
I get the same error, for a couple of weeks now, when trying to run an app from the master channel.
I got it working by forcing the web renderer to be HTML:
flutter run -d chrome --no-sound-null-safety --web-renderer=html
When you build your app for web you should:
flutter build web --no-sound-null-safety --web-renderer=html
By default the web renderer is auto, choosing the canvaskit web renderer on desktop browsers and html on mobile.
If you want to avoid this altogether you can stay on the beta or dev channels.
if it is working with another image then it should be a server-side error where the image is stored.
Could be an issue with the codec format. Try running the same code with another image url. If it is working, then the above error could be a technical glitch.
You could try this widget
https://pub.dev/packages/meet_network_image
You can just use this package https://pub.dev/packages/image_network
Using HTML renderer might break other things (like SVG rendering in my case)
Try not to define height, width for container and add fit:BoxFit.cover as a parameter of NetworkImage

Check for color during widget test?

The goal is to verify the color of a RaisedButton.icon
During my widget tests, I have the ability to look for text with find.text as well as icons with find.byIcon. There is no built in method for finding color.
How does one do the equivalent of find.color?
And example of my code is
RaisedButton.icon(
color: Color(_isAttendingEvent ? 0xFFD9FFB3 : 0xFFE3FFC7),
icon: Icon(_isAttendingEvent ? Icons.star : Icons.star_border),
label: Text(
_isAttendingEvent ? 'Attending' : 'Attend',
),
),
I'm trying to determine whether there is color: Color(0xFFD9FFB3) or color: Color(0xFFE3FFC7)
And I'm not sure if this is possible
I am not sure with RaisedButton.icon, but if it is just an icon you can try using:
expect((tester.firstWidget(find.byType(Icon)) as Icon).color, Color(0xFFE3FFC7));
If it not the first icon widget that appears on your screen, you can specific an index of it by:
expect((tester.widget(find.byType(Icon).at(/*index*/)) as Icon).color, Color(0xFFE3FFC7));
Note: To find a widget colour, you need to cast that widget to be something that contain a color property
For example:
To find Material color you can use:
expect((tester.firstWidget(find.byType(Material)) as Material).color, Colors.black);
To find Container with BoxDecoration color:
expect(((tester.firstWidget(find.byType(Container)) as Container).decoration
as BoxDecoration).color, Colors.black);
To find Text color:
expect(((tester.firstWidget(find.text('text')) as Text).style).color, Colors.black);
To find Appbar Material. color
final appbar = tester.widget<AppBar>(find.byKey(Key("appbar")));
expect(appbar.backgroundColor,Colors.white);
To find Text color Material
final text = tester.widget<Text>(find.text("text"));
expect(text.style.color, Colors.grey);
expect(text.style.fontSize, 15);
Update you flutter version. It's working now, i am able to access color in widget test. My current flutter version is "Flutter 1.15.18 • channel dev".
Earlier it was not working with version "Flutter v1.12.13+hotfix.5"
Hope this will help. More details here
If you're using a TextButton, ElevatedButton, or Outlined button, the background color will be a MaterialStateProperty. You can verify the color in almost the same way as mentioned above:
expect(
tester.widget(textButton.first),
isA<TextButton>().having(
(w) => w.style?.backgroundColor?.resolve({}),
'button color',
Colors.grey,
));

How can I justify text with Flutter markdown?

I started using flutter markdown, however I'd like to justify the content, and I couldn't until now.
I tried using a Center and Alignment but didn't work.
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
class OutsideBankHourDescription extends StatelessWidget {
#override
Widget build(BuildContext context) {
String text =
"Antecipações em __horários__ bancários acontecem em 1h na média. __Fora do horário bancário__ o saldo estará em sua conta __no dia seguinte.__";
return Expanded(
child: Container(
alignment: Alignment.center,
child: Markdown(
styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context)),
data: text,
),
),
);
}
}
It's not available for now to change text alignment in flutter_markdown 0.2.0.
You must contact the authors of this plugin to request this feature.
But if you need fast fix, you can add textAlign: TextAlign.center attribute in source code of this file: https://github.com/flutter/flutter_markdown/blob/master/lib/src/builder.dart
Line of code: 345
mergedTexts.add(new RichText(text: mergedSpan, textAlign: TextAlign.center));
Result:
For more elegant way you must clone git repository of this plugin, attach to your project directly and work to add text alignment feature on your own.
It becomes possible to set up proper text alignment with flutter_markdown.
var style = MarkdownStyleSheet(
textAlign: WrapAlignment.center,
h1Align: WrapAlignment.center,
);
Markdown(
styleSheet: style,
data: '# header1 is center-aligned\ntext body is also center-aligned'
);
You can customized your styles with all the other optional parameters provided by MarkdownStyleSheet class.

Starting with plain (non material ui) canvas in flutter

All tutorials and documentation I've seen so far start of with importing flutter material. I am wondering is this an absolute requirement? What if I want to start with a plain canvas and build my own theme / widgets. Can I do this, if so what package should be used here so I get access to default widgets?
Although the answers here are correct, I want to add a few more points. To use raw widgets use import 'package:flutter/widgets.dart';
Here is a working example:
import 'package:flutter/widgets.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(25.0),
child: Directionality(
textDirection: TextDirection.ltr,
child:Text("hello world",
style: TextStyle(
color: Color.fromRGBO(255, 255, 255, 1)
),
)));
}
}
The directionality is needed, the padding was added so that we see the message, otherwise it is masked by the menubar in phone.
Widgets in flutter makes the developers day easy. All the widgets are built on top dart:ui lib. It is up to you, to decide to use existing set of widgets or develop your ui from scratch. Flutter does not stop you from writing your own widgets.
You can find a few raw example of here, that does not use any widgets at all.
If you simple don't want only material widgets, then you can just build your own themed widgets with all other basic widgets and layouts available in flutter.
If you wanted to build few of your own widgets with a canvas and use it along with other widgets in flutter, you look into CustomPaint and CustomPainter widgets.
Hope this helped!
Just as Chandan Purohit answered, use import 'package:flutter/widgets.dart';. Flutter official gives a minimal app in Introduction to widgets as follows:
import 'package:flutter/material.dart';
void main() {
runApp(
const Center(
child: Text(
'Hello, world!',
textDirection: TextDirection.ltr,
),
),
);
}
Just change flutter/material.dart to flutter/widgets.dart, and you get a plain canvas to start.
Note: The color of Text is white by default.