Test is not using same asset as application in flutter local package - flutter

I moved the login screen of my application to a local package and the image on that screen is still showing without changing its path ('assets/images/logo.png').
But when I added a widget test in the package I had error: Unable to load asset.
Here's the project structure:
|-- assets
|-- images
|-- logo.png <-- the image
|-- lib
|-- packages
|- login_screen <-- the local package
and the pubspec.yaml:
dependencies:
flutter:
sdk: flutter
login_screen:
path: packages/login_screen
flutter:
assets:
- assets/images/
login_screen.dart:
class LoginScreen extends StatelessWidget {
const LoginScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: const EdgeInsets.all(50),
child: Column(
children: [
Image.asset('assets/images/logo.png'),
Spacer(),
OutlinedButton(onPressed: (){}, child: Text('Login')),
],
),
),
);
}
}
The first thing I did is to move the image into the package and updated its pubspec.yaml to use the asset. That fixed the test issue but broke the application which couldn't find the asset anymore.
I did read a lot to understand how packages work in Flutter but I couldn't make it. The only way to make both app and test work is duplicating the asset.
Am I missing something?

You can try these steps after adding new assets:
Stop debug or uninstall the app from the phone or emulator
Flutter clean, flutter pub get
Start debug

Related

Flutter (Unable to load asset)

I'm unable to load images to my app although I tried many solutions
my code is
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.amber,
appBar: AppBar(
backgroundColor: Colors.amber[900],
title: const Text("hi"),
),
body: Image(image: AssetImage("images/ab.png"),
),
),
);
}
}
this is my pubspec.yaml
flutter doctor
1- I used $ flutter clean and then $ flutter pub get.
2- I updated flutter SDK.
3- I mention only the folder (images).
4- I used a smaller image.
5- I restarted my laptop.
6- I run my code in another IDE.
but nothing is working for me, so can anyone help me?
thanks in advance
I copied your main.dart code, I created a images folder with a .png file.
I think the problem could be the position of the images folder, you should place it beside the lib folder.
Without seeing the project folder structure I cannot be sure, but if you do it like that your code should work fine.
Here's the pubspec.yaml:
flutter:
assets:
- images/
Here's a screenshot of the your code running:

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

How to add SVGs to AppBar class in 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'),

SelectableText.rich in Flutter

I want to make 3 texts that are copyable and I want to choose SelectableText.rich.
So you can choose what you want to copy.
class HomeScreen extends StatelessWidget{
#override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(title: new Text ("Better Hashtag"), backgroundColor: Colors.red),
body: Column(
children: <Widget>[
SelectableText.rich(Textspan (
)
);
],
),
);
}
}
I get an error by SelectableText.rich
What error are you getting?
Have you added the flutter_selectedtext dependency to your pubspec.yaml file?
flutter_selectext: ^0.1.1
More info: https://pub.dev/packages/flutter_selectext
You also have a syntax problem:
body: Column(
children: <Widget>[
SelectableText.rich(Textspan (
)
); // <----- remove this semi-colon, as you are still
// in the list of children of the Column widget.
],
),
SelectableText is included in Flutter 1.9 release. So if you are using Flutter 1.9 or above, you don't need to add any dependency to your pubspec.yaml file, can just use it directly.
If you are not sure about the syntax, check out this example: https://api.flutter.dev/flutter/material/SelectableText-class.html#material.SelectableText.2
If you are using an older version of Flutter and getting the error, run flutter upgrade. Once complete it should work. As of the date of this response, Flutter stable channel is on 1.9.1. So no matter which channel you are using, as soon as you upgrade Flutter, you should have SelectableText.rich ready to use without having to add any dependency to your pubspec.yaml file.

How to add image in Flutter

I am developing Flutter app for the first time. I have an issue adding an image. I have a following questions:
Where to create an images folder?
Where to add assets tag in pubspec.ymal?
Is there any assets folder needed for this?
What I tried:
assets:
- images/lake.jpg
inside pubspec.ymal :
Full file :
name: my_flutter_app
description: A new Flutter application.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true,
assets:
- images/lake.jpg
Error log :
#/properties/flutter/properties/uses-material-design: type: wanted [boolean] got true,
Error detected in pubspec.yaml:
Error building assets
FAILURE: Build failed with an exception.
* Where:
Script '/home/abc/Downloads/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 435
* What went wrong:
Execution failed for task ':app:flutterBuildDebug'.
> Process 'command '/home/abc/Downloads/flutter/bin/flutter'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
BUILD FAILED in 1s
Finished with error: Gradle build failed: 1
My main.dart code :
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
// Uncomment lines 7 and 10 to view the visual layout at runtime.
//import 'package:flutter/rendering.dart' show debugPaintSizeEnabled;
void main() {
//debugPaintSizeEnabled = true;
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
Widget titleSection = new Container(
padding: const EdgeInsets.all(32.0),
child: new Row(
children: [
new Expanded(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Container(
padding: const EdgeInsets.only(bottom: 8.0),
child: new Text(
'Oeschinen Lake Campground',
style: new TextStyle(
fontWeight: FontWeight.bold,
),
),
),
new Text(
'Kandersteg, Switzerland',
style: new TextStyle(
color: Colors.grey[500],
),
),
],
),
),
new Icon(
Icons.star,
color: Colors.red[500],
),
new Text('41'),
],
),
);
Column buildButtonColumn(IconData icon, String label) {
Color color = Theme.of(context).primaryColor;
return new Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
new Icon(icon, color: color),
new Container(
margin: const EdgeInsets.only(top: 8.0),
child: new Text(
label,
style: new TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w400,
color: color,
),
),
),
],
);
}
Widget buttonSection = new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
buildButtonColumn(Icons.call, 'CALL'),
buildButtonColumn(Icons.near_me, 'ROUTE'),
buildButtonColumn(Icons.share, 'SHARE'),
],
),
);
Widget textSection = new Container(
padding: const EdgeInsets.all(32.0),
child: new Text(
'''
Lake Oeschinen lies at the foot of the Blüemlisalp in the Bernese Alps. Situated 1,578 meters above sea level, it is one of the larger Alpine Lakes. A gondola ride from Kandersteg, followed by a half-hour walk through pastures and pine forest, leads you to the lake, which warms to 20 degrees Celsius in the summer. Activities enjoyed here include rowing, and riding the summer toboggan run.
''',
softWrap: true,
),
);
return new MaterialApp(
title: 'Flutter Demo',
home: new Scaffold(
appBar: new AppBar(
title: new Text('Top Lakes'),
),
body: new ListView(
children: [
new Image.asset(
'images/lake.jpg',
width: 600.0,
height: 240.0,
fit: BoxFit.cover,
),
titleSection,
buttonSection,
textSection,
],
),
),
);
}
}
I am referring to this tutorial https://flutter.io/tutorials/layout/
Also, I want to ask if there are any tools for a clean rebuild in a flutter as I can't find any options for this.
How to include images in your app
1. Create an assets/images folder
This should be located in the root of your project, in the same folder as your pubspec.yaml file.
In Android Studio you can right click in the Project view
You don't have to call it assets or images. You don't even need to make images a subfolder. Whatever name you use, though, is what you will register in the pubspec.yaml file.
2. Add your image to the new folder
You can just copy your image into assets/images. The relative path of lake.jpg, for example, would be assets/images/lake.jpg.
3. 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/images/lake.jpg
If you have multiple images 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/images/
Note: Make sure to use the exact number of spaces. That's 2 spaces per indentation.
4. Use the image in code
Get the asset in an Image widget with Image.asset('assets/images/lake.jpg').
The entire main.dart file is here:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Image from assets"),
),
body: Image.asset('assets/images/lake.jpg'), // <--- image
),
);
}
}
5. Restart your app
When making changes to pubspec.yaml I find that I often need to completely stop my app and restart it again, especially when adding assets. Otherwise I get a crash.
Running the app now you should have something like this:
Further reading
See the documentation for how to do things like provide alternate images for different densities.
Videos
The first video here goes into a lot of detail about how to include images in your app. The second video covers more about how to adjust how they look.
Flutter Tutorial - 1/2 Image - Deep Dive
Flutter Tutorial - 2/2 Image - Deep Dive
I think the error is caused by the redundant ,
flutter:
uses-material-design: true, # <<< redundant , at the end of the line
assets:
- images/lake.jpg
I'd also suggest to create an assets folder in the directory that contains the pubspec.yaml file and move images there and use
flutter:
uses-material-design: true
assets:
- assets/images/lake.jpg
The assets directory will get some additional IDE support that you won't have if you put assets somewhere else.
Create images folder in root level of your project.
Drop your image in this folder, it should look like
Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.
flutter:
uses-material-design: true
# add this
assets:
- images/profile.jpg
Tap on Packages get at the top right corner of the IDE.
Now you can use your image anywhere using
Image.asset("images/profile.jpg")
The problem is in your pubspec.yaml, here you need to delete the last comma.
uses-material-design: true,
To use image in Flutter. Do these steps.
1. Create a Directory inside assets folder named images. As shown in figure below
2. Put your desired images to images folder.
3. Open pubpsec.yaml file . And add declare your images.Like:--
4. Use this images in your code as.
Card(
elevation: 10,
child: Container(
decoration: BoxDecoration(
color: Colors.orangeAccent,
image: DecorationImage(
image: AssetImage("assets/images/dropbox.png"),
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
),
),
child: Text("$index",style: TextStyle(color: Colors.red,fontSize: 16,fontFamily:'LangerReguler')),
alignment: Alignment.center,
),
);
An alternative way to put images in your app (for me it just worked that way):
1 - Create an assets/images folder
2 - Add your image to the new folder
3 - Register the assets folder in pubspec.yaml
4 - Use this code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
var assetsImage = new AssetImage('assets/images/mountain.jpg'); //<- Creates an object that fetches an image.
var image = new Image(image: assetsImage, fit: BoxFit.cover); //<- Creates a widget that displays an image.
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Climb your mountain!"),
backgroundColor: Colors.amber[600], //<- background color to combine with the picture :-)
),
body: Container(child: image), //<- place where the image appears
),
);
}
}
Create your assets directory the same as lib level
like this
projectName
-android
-ios
-lib
-assets
-pubspec.yaml
then your pubspec.yaml like
flutter:
assets:
- assets/images/
now you can use Image.asset("/assets/images/")
--> Follow Below Steps One OR Multiple Image Insertion.:
-> Create 'assets/images' folder as in project module.
-> put images which you want.
-> use of image using this syntax. ex.
- Image.asset('assets/images/tony.jpg')
-> use image avatar which you want like, circle, square and much more as your need.
-> Open 'pubspec.yaml' file
-> write the code in 'flutter:' section. ex.
-------------------------------
uses-material-design: true
assets:
- assets/images/ // if multiple images you have then
- assets/images/imagename.extension // if single images you have then
-------------------------------
-> click on 'PUB GET' button which occurs on Right side of Screen above.
-> Run App.
-> if you get any issue then
-> Go to file -> Invalid caches/Restart -> Invalid Caches/Restart button
-> Done.
See Below Images to Get a Better idea of Implementation.
•• Here, add image file like below. ••
•• Here, add image file Description in PUBSPEC.YAML file like below. ••
Done.☻♥
When you adding assets directory in pubspec.yaml file give more attention in to spaces
this is wrong
flutter:
assets:
- assets/images/lake.jpg
This is the correct way,
flutter:
assets:
- assets/images/
their is no need to create asset directory and under it images directory and then you put image.
Better is to just create Images directory inside your project where pubspec.yaml exist and put images inside it
and access that images just like as shown in tutorial/documention
assets:
- images/lake.jpg // inside pubspec.yaml
If the image is inside a package dependency, you should also provide the package name, event if you are referencing the image from the same dependency!
Image.asset("assets/pics/events_empty.png", package: "ui_elements"),
Ref:
Asset images in package dependencies
Make sure you create the assets folder in the main directory, not in the lib folder.
you can rather use this to see access to everything inside assets, because there may be folders like images, logo, icon, etc...
create the assets folder in the root of the project
MyProject
android
assets
ios
lib
test
web
windows
.gitignore
pubspec.yaml
and in your pubspec.yaml, there are
assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
replace the last two lines by the 'assets/' to be able to directly access everything inside assets
if you have directly images in assets
assets:
- assets/
or if you have sub folders in assets
assets:
- assets/folder1/
- assets/folder2/
- assets/folder3/
Create an assets/images folder and Add your image to the folder
Register the assets folder in pubspec.yaml
flutter:
assets:
- assets/images/placeholder_circle_image.png
If you have multiple images
flutter:
assets:
- assets/images/
Use the image in code
Image.asset(
'assets/images/item_entry/add_car_video.png',
width: 100,
height: 100,
fit: BoxFit.cover,
cacheWidth:100 * MediaQuery.of(context).devicePixelRatio.round(),
),
Error when comma is at the end of below line
uses-material-design: true,
when the line after assets: indent is not correct it throws below error
If the indent is corrected as shown in below, then error is fixed.
If the asset file is not added then it highlights that with yellowish background but Pub get doesn't throw error but there will be an error during installation.
In short, Code Indent and syntax is important
You can create a folder and reference it as shown