I create a swift package in my work space.
I followed this guide just to test things out:
https://sarunw.com/posts/how-to-modularize-existing-ios-projects-using-swift-package/
All went well.
One of the things I added to the package is:
public extension Color {
static let customRed:Color = Color(uiColor: UIColor(named: "customRed", in: .module, compatibleWith: nil)!)
}
I deleted the customRed from the Assets.xcassets in my main app after I added the Assets to the actual package.
Everything works fine now and the package uses the customRed as defined in the package Assets.xcassets.
I have a lot files that use that Color.customRed in the app and I was thinking I had to go to each file and add the import statement for the package at the top. So:
import MyColorPackage
Question: I don't understand why the app works fine without doing that. Files can use the Color.customRed call without adding the import MyColorPackage at the top of the file that uses it. How can files use that customRed without having the import MyColorPackage in the file? App runs fine without importing the module in the files that use the customRed. Why?
The reason for this is due to a longstanding swift bug so you’re not doing anything wrong per se. It has various forms, some fixed over the years, some not but in your case what happens is that the first file in your main project that imports MyColorPackage will cause the whole rest of the project to “see” that Color extension. In my experience this happens only with public extensions nowadays and your package happens to do just that - declare a public extension to SwiftUI’s Color
If you add some public entity in that package, say …
import SwiftUI
public enum MyColorTheme {
public static let myThemeButtonsColor = Color.green
}
… then you won’t be able to use MyColorTheme in any file that doesn’t import MyColorPackage, as per what is intuitively normal.
I would suggest to still add the missing imports whenever you use symbols from that package as this issue might be fixed in a future version and your project will fail to build
Reference: https://github.com/apple/swift/issues/46493
I have a text file (.txt) that I'd like to be an asset that I can scan in later.
In the pubspec.yaml, I've made sure that:
flutter:
assets:
- res/my_file.txt
exists. The file resides in the res/ folder that I made, on the same level as lib/android/ and ios/
I'm trying to read the file from a custom class, not a widget.
According to the documentation, I'm to use this import:
import 'package:flutter/services.dart' show rootBundle;
and start reading like so:
/// Assumes the given path is a text-file-asset.
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
And to get the actual data, do:
String data = await getFileData(fileName);
However, when I use a fileName like 'assets/res/my_file.txt', I get an error: Unable to load asset: assets/res/my_file.txt.
It's also worth noting that I'm trying to do this from a unit test. Any ideas on how to properly do this? Thanks!
Here is a fuller answer for future visitors.
Create an assets folder
Create an assets folder in your project's root folder. In Android Studio you can right click the Project outline and go to New > Directory.
You can create another subfolder for text files in assets if you like. But if you do, you have to include the relative path in pubspec.yaml. See below.
Add your text file to the new folder
You can just copy your text file into the assets directory. The relative path of my_file.txt, for example, would be assets/my_file.txt.
Register the assets folder in pubspec.yaml
Open the pubspec.yaml file that is in the root of your project.
Add an assets subsection to the flutter section like this:
flutter:
assets:
- assets/my_file.txt
If you have multiple files that you want to include, then you can leave off the file name and just use the directory name (include the final /):
flutter:
assets:
- assets/
Get the text in code
You can use the global rootBundle to get the text file asset:
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/my_text.txt');
}
Or if you have the BuildContext (inside a widget) you can use DefaultAssetBundle. This is recommended because it allows switching asset bundles at runtime, which is useful for multilingual assets.
Future<String> loadAsset(BuildContext context) async {
return await DefaultAssetBundle.of(context).loadString('assets/my_text.txt');
}
See also
Loading text assets
How to include images in your app
The folder name "assets" isn't magically added. Update your pubspec.yaml to include the full path to the asset.
flutter:
assets:
- assets/res/my_file.txt
In my opinion, in order to load a js file into a flutter, you should consider it as a text file and load it properly. So, you need to add the file to assets folder, add into a pubspec file, then load it. read the full answer here
Second, you used evalJavascript. this function can be used in many different situations. but it will work only if you have a view panel.
Check below example:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
main() async {
String jsCode = await rootBundle.loadString('assets/javascript.js');
runApp(new MaterialApp(
home: LunchWebView(jsCode),
));
}
class LunchWebView extends StatelessWidget {
final String text;
LunchWebView(this.text);
#override
Widget build(BuildContext context) {
final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
flutterWebviewPlugin.launch('https://www.google.com');
flutterWebviewPlugin.evalJavascript(text);
return Container();
}
}
I tried adding an image with a SVG source to my flutter application.
new AssetImage("assets/images/candle.svg"))
But I didn't get any visual feedback.
How can I render an SVG picture in Flutter?
Fonts are a great option for a lot of cases.
I've been working on a library to render SVGs on a canvas, available here:
https://github.com/dnfield/flutter_svg
The API as of right now would look something like
new SvgPicture.asset('asset_name.svg')
to render asset_name.svg (sized to its parent, e.g. a SizedBox). You can also specify a color and blendMode for tinting the asset..
It's now available on pub and works with a minimum of Flutter version 0.3.6. It handles a bunch of cases but not everything - see the GitHub repo for updates and to file issues.
The original GitHub issue referenced by Colin Jackson is really not meant to be primarily focused on SVG in Flutter. I opened another issue here for that: https://github.com/flutter/flutter/issues/15501
Flutter does not currently support SVG. Follow issue 1831 for updates.
If you absolutely need vector drawing you can see the Flutter Logo widget as an example of how to draw using the Canvas API, or rasterize your image on the native side and pass it to Flutter as a bitmap, but for now your best bet is probably to embed high-resolution rasterized asset images.
Developers from the Flutter community created a lib to handle svg files. We can use it as
new SvgPicture.asset(
'assets/images/candle.svg',
height: 20.0,
width: 20.0,
allowDrawingOutsideViewBox: true,
),
I found a small example of SVG implementation here.
The work around for now is use fonts
https://icomoon.io/
fonts:
- family: icomoon
fonts:
- asset: assets/fonts/icomoon.ttf
Useage
static const IconData TabBarHome= const IconData(0xe906, fontFamily: 'icomoon');
static const IconData TabBarExplore= const IconData(0xe902, fontFamily: 'icomoon');
Replace the ### eg (906)
You can follow the below steps
- visit http://fluttericon.com
- upload your SVG icons
- click on download button
- you will get two files
1. iconname.dart 2. iconname.ttf font file
- use this file in flutter & import iconname.dart
step 1. add dependency in your pubspec.yaml
dependencies:
flutter_svg: any
the Advantage of version any is you can use in any SDK version
but dependencies version is most important so add suitable version for your dependency.
step 2. import the flutter svg package in your app
import 'package:flutter_svg/flutter_svg.dart';
step 3. just use like below
SvgPicture.asset(
'assets/images/bm-icon1.svg',
width: 18.0,
height: 18.0,
),
You can use this library for rendering SVG Images - https://pub.dev/packages/flutter_svg
Example -
Container(
child: SvgPicture.asset("assets/images/yourImage.svg")
)
I solved similar problem by converting the svg images to ttf at fluttericon.com.
These are the steps involved.
Keep all your svg files in a folder.
Upload all of them to fluttericon by using the uploader there.
You can select all of them and drag and drop at the spot.
Give your icons a dart class name at the top: like, Svgicons
Select all your icons and press Download.
It will download a zip file with a dart file and fonts folder which contains Svgicons.ttf.
copy the fonts folder to your project folder and refer to it as an asset in pubspec.yaml.
fonts:
- family: Svgicons
fonts:
- asset: fonts/Svgicons.ttf
import the svgicons_icons.dart where you are going to use the images.
Sample:
import '../svgicons_icons.dart';
import 'social_media.dart';
class SocialMediaRepository {
List<SocialMedia> getSocialMedia = [
SocialMedia(id: 1, title: "Facebook", iconAsset:Svgicons.facebook, isFavorite: false),
SocialMedia(id: 2, title: "Instagram", iconAsset: Svgicons.instagram, isFavorite: false),
SocialMedia(id: 3, title: "LinkedIn", iconAsset: Svgicons.linkedin, isFavorite: false),
....
Here iconAsset is of type IconData which used to be a String referring to the svg image originally.
Display the ttf by using
...
Icon(item.iconAsset),
SizedBox(width: 10),
Text(item.title),
],
),
where item is the object containing IconData.
Now you can remove the reference to svg images from the project.
You can use flare to create animations and just import .flr as an asset
import 'package:flare_flutter/flare_actor.dart';
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return new FlareActor("assets/Filip.flr", alignment:Alignment.center, fit:BoxFit.contain, animation:"idle");
}
}
visit flare_flutter https://pub.dev/packages/flare_flutter
Of possible interest: There's a newer Flutter SVG library called jovial_svg. I wrote it to handle a more robust subset of SVG than what I was able to find on pub.dev at the time. While I was at it, I also made a binary format that SVG assets can be compiled to. It's a little more compact, and about 10x faster to read, so it's a good choice for assets you package with your application.
The library is at https://pub.dev/packages/jovial_svg
flutter support special type of svg
if have style tag then not load svg image in flutter
flutter support inline styling in svg
Svg in flutter https://pub.dev/packages/flutter_svg
add package in pubspec.yaml
dependencies:
flutter_svg: any
assets:
-assets/images/
to insert svg.
SvgPicture.asset('assets/images/password-icon.svg',
width: 24, height: 29.2),
How can import and use any third party javascript libraries in dart..? I want to use snapsvg in my dart application to render svg. But not sure how to add dependencies to add and import it.
I added js: any to my pubspec.yaml and imported packages/browser/interop.js into my html. Where do I place downloaded snapsvg.js and import it to my dart source file to use it.
I am trying to use following javascript code using snapsvg framework from dart.
s = Snap(800, 600);
s.rect(0, 0, 100, 100).attr({
fill: 'white',
stroke: 'black'
});
I tried this code from in dart:
import 'package:js/js.dart' as js;
void main() {
var s = js.context.Snap(800, 600);
s.rect(0, 0, 100, 100);
}
This works fine in dartium, but when I Run as Javascript after build, I got javascript error "method zm not found in object"
I believe this is not right way and I should use be using callMethod on proxy. So I changed code like this
import 'dart:js' show context, JsObject;
void main() {
var snap = context['Snap'];
snap.callMethod('rect', 0,0,100,100);
}
This is not working in Dartium as itself. I would appreciate if someone can provide example of how to call constructor Snap(800, 600) from dart and also rect and attr methods in my example code.
You add them to the HTML file using <script> tags.
You can call JavaScript functions from Dart using dart-js-interop.
There are many examples here on Stackoverflow under this tag - just click on the tag below your question.
When you provide a more concrete example it is easier to help.
You can call into JavaScript with the built-in dart:js library. Please try to avoid using /package/ js, which is what you install by adding js: any to your pubspec. The js package is likely to cause the dart2js output to be bloated and we're probably going to deprecate it at some point.
You can reference JavaScript files like you would in any HTML page, via script tags. You don't actually import them into Dart source, you use dart:js to access JavaScript via its top-level context property.
I have the demo code for the Rikulo UXL ScrollView demo working with the Dart Editor.
UXL Overview
However, the set-up seems cumbersome to me. For the example to build the .Dart file from the UXL file, (apparently) it needs to be named as: "ScrollView.uxl.xml". Can the build process or Dart Editor be configured and set-up to do a more streamlined workflow like:
ScrollView.uxl --> ScrollView.dart
As opposed to the current rule:
ScrollView.uxl.xml --> ScrollView.uxl.dart
It seem to me the solution seems to lie in the UXL builder:
import 'package:rikulo_uxl/uc.dart';
Solutions welcome.
The readme of the package seems to contain exactly the code you are looking for:
https://github.com/rikulo/uxl
add this to your build.dart file (in the directory where your pubspec.yaml file is
import 'package:rikulo_uxl/uc.dart' show build;
void main(List<String> arguments) {
build(arguments);
}