Flutter with UI Avatar returning invalid image - laravel

I am working on pulling my user profiles into my flutter app, but for some reason I am getting image invalid when using Image.Network when the user's profile photo is coming from ui-avatars.com, it works fine when it is just returning a jpg.
FutureBuilder<User>(
future: futureUser,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Image.network(
snapshot.data!.profilePhotoUrl,
fit: BoxFit.cover,
width: 90,
height: 90,
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
For reference here is the URL that is being returned in the users profile from ui-avatars: https://ui-avatars.com/api/?name=m&color=7F9CF5&background=EBF4FF
Error in console:
Exception caught by image resource service
The following _Exception was thrown resolving an image codec:
Exception: Invalid image data
When the exception was thrown, this was the stack:
#0 _futurize (dart:ui/painting.dart:5886:5)
#1 ImageDescriptor.encoded (dart:ui/painting.dart:5741:12)
#2 instantiateImageCodecFromBuffer (dart:ui/painting.dart:2092:60)
#3 PaintingBinding.instantiateImageCodecFromBuffer (package:flutter/src/painting/binding.dart:153:15)
#4 NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:135:22)
<asynchronous suspension>
Image provider: NetworkImage("https://ui-avatars.com/api/?name=m&color=7F9CF5&background=EBF4FF", scale: 1.0)
Image key: NetworkImage("https://ui-avatars.com/api/?name=m&color=7F9CF5&background=EBF4FF", scale: 1.0)
Test Screen
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Test',
home: Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Image.network(
'https://ui-avatars.com/api/?name=m&color=7F9CF5&background=EBF4FF',
fit: BoxFit.cover,
width: 90,
height: 90,
),
),
);
}
}
Any help would be greatly appreciated, I am fairly new to Flutter.

Related

How to embed watermark (Text or Image) in Flutter

I created an app with image picker and I want to embed a text or image to that selected picture and saved it to gallery.
👇 My App
👇 I tried to create this
This is the code I used for image picker
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Watermark',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File _pickedImage;
Future pickAnImage() async {
final pickedFile =
await ImagePicker().getImage(source: ImageSource.gallery);
setState(() {
_pickedImage = File(pickedFile.path);
});
}
_saveImage() {
//TODO: Save image to gallery
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text("Flutter Watermark"),
),
body: SingleChildScrollView(
child: Center(
child: Column(
children: <Widget>[
_pickedImage == null
? TextButton(
child: Text("Pick an Image"),
onPressed: pickAnImage,
)
: Column(
children: [
Image.file(_pickedImage),
SizedBox(
height: 50.0,
),
TextButton(
onPressed: _saveImage, child: Text("Save Image"))
],
),
],
),
),
),
),
);
}
}
I followed the below tutorial but it is freeze the app and I couldn't implement it.
Tutorial
https://medium.com/flutter-community/add-watermark-over-image-in-flutter-e7353e3cf603
Can anyone help me please?
You can try using this dependency:
As suggested by the author, this example is similar to your query
import 'dart:io';
import 'package:image/image.dart';
void main() {
// Create an image
Image image = Image(320, 240);
// Draw some text using 24pt arial font
drawString(image, arial_24, 0, 0, 'Hello World');
// Save the image to disk as a PNG
File('test.png').writeAsBytesSync(encodePng(image));
}
Image downloaded from this link.

Flutter images download again on navigator pop

Hi i have a problem with a stream of images in flutter, when i do a Navigator.push() and then Navigator.pop() the images of the stream gets reload.
My Class is a Stateful Widget with AutomaticKeepAliveClientMixin
When images gets donwloaded
After a Navigator.push() and then Navigator.pop()
I use riverpod for the stream and Firebase Storage.
Expanded(
child: watch(userEventsFamilyStream(user.uid)).maybeWhen(
data: (events) {
if (events.isEmpty) {
return EmptyGrid(
onTap: () => context
.read(menuNotifier)
.currentIndex = 1);
}
return Stack(
children: [
GridView.count(
crossAxisCount: 3,
children: [
...events.map((event) {
return EventItem(
uid: event.uid,
imgUrl: event.imgUrl,
onTap: () async {
final result =
await buildOptions(context);
_handleResult(
context, result, actions, event);
},
);
}).toList()
],
),
if (state.isSubmitting)
Container(
decoration: const BoxDecoration(
color: Colors.black54),
width: MediaQuery.of(context).size.width,
child: const Center(
child: CircularProgressIndicator())),
],
);
},
orElse: () =>
const Center(child: CircularProgressIndicator())),
),
I also use cached_network_image package
Hero(
tag: '${uid}profile',
child: FadeInImage(
placeholder: const AssetImage('assets/img/transparent.png'),
image: CachedNetworkImageProvider(imgUrl),
fit: BoxFit.cover,
),
),
if you want to keep the state of the page alive, you may use AutomaticKeepAliveClientMixin
class Foo extends StatefulWidget {
#override
FooState createState() {
return new FooState();
}
}
class FooState extends State<Foo> with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
return Container();
}
#override
bool get wantKeepAlive => true;
}
I solved: the problem was the size of the images, even cached if the image is too big it takes some time to get load.

How to play and control gif with CachedNetworkImage in Flutter?

I'm currently developing an app for deaf people and I need to use many gifs inside my app.
I don't want my gifs to play more than once so I used GifImage which lets me control the number of reproductions and the speed of the gif locally.
Now I realize that with so many gifs, my app will be too heavy to upload to the stores, so I tried using CachedNetworkImage to play my gifs from firebase storage. The problem with this library is that I have no control on the reproduction of the gifs, they play infinitely.
What I have already tried:
Play gif from local file:
GifImage(
controller: controller,
image: AssetImage('test.gif'),
)
Play gif using CachedNetworkImage:
CachedNetworkImage(
imageUrl:
'https://firebasestorage.googleapis.com/v0/b/app-lsc-7310d.appspot.com/o/test.gif?alt=media',
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width * 0.5,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
),
I want to know if it is possible to use both libraries together so I can store the gifs in the cache and also have control over them, like so:
CachedNetworkImage(
imageUrl:
'https://firebasestorage.googleapis.com/v0/b/app-lsc-7310d.appspot.com/o/test.gif?alt=media',
imageBuilder: (context, imageProvider) => GifImage(
controller: controller,
image: imageProvider,
),
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
),
But I get the following error:
[VERBOSE-2:shell.cc(242)] Dart Unhandled Exception: NoSuchMethodError: The getter 'buffer' was called on null.
Receiver: null
Tried calling: buffer, stack trace: #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 fetchGif (package:flutter_gifimage/flutter_gifimage.dart:243:76)
#2 GifImageState.didChangeDependencies (package:flutter_gifimage/flutter_gifimage.dart:158:7)
#3 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4653:11)
#4 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4469:5)
#5 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3541:14)
#6 Element.updateChild (package:flutter/src/widgets/framework.dart:3303:20)
#7 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5981:14)
#8 Element.updateChild (package:flutter/src/widgets/framework.dart:3293:15)
#9 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4520:16)
#10<…>
Here is the full code in case you want to try it out:
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
GifController controller;
String currentGif = 'test';
double frameNum = 25.0;
void initState() {
controller = GifController(vsync: this);
super.initState();
}
playGif(String gifToPlay) async {
controller.value = 0;
controller.animateTo(frameNum - 1,
duration: Duration(milliseconds: (160 * (frameNum - 1)).toInt()));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Giphy'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CachedNetworkImage(
imageUrl:
'https://firebasestorage.googleapis.com/v0/b/app-lsc-7310d.appspot.com/o/test.gif?alt=media',
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width * 0.5,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
),
SizedBox(
height: 20.0,
),
Card(
child: GifImage(
controller: controller,
image: AssetImage('images/test.gif'),
),
elevation: 7,
),
SizedBox(
height: 20.0,
),
GestureDetector(
onTap: () {
playGif(currentGif);
},
child: Container(
color: Colors.blueGrey,
padding: EdgeInsets.all(5.0),
child: Text(
'Play Local Gif',
style: TextStyle(fontSize: 20),
),
),
),
],
),
),
);
}
}
I am open to other suggestions as well and would be really grateful for your help.

Flutter: How to put button on each image like (x) to cancel selected image

I am using multi_image_picker 4.6.1 in my application but I faced little problem. How to organize images on specific place on the page and put cancel button on each selected image so user can cancel or remove selected image one by one like in picture here. Thanks in advance
here is the code i am using
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:multi_image_picker/multi_image_picker.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Asset> images = List<Asset>();
String _error = 'No Error Dectected';
#override
void initState() {
super.initState();
}
Widget buildGridView() {
return GridView.count(
crossAxisCount: 3,
children: List.generate(images.length, (index) {
Asset asset = images[index];
return AssetThumb(
asset: asset,
width: 300,
height: 300,
);
}),
);
}
Future<void> loadAssets() async {
List<Asset> resultList = List<Asset>();
String error = 'No Error Dectected';
try {
resultList = await MultiImagePicker.pickImages(
maxImages: 300,
enableCamera: true,
selectedAssets: images,
cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
materialOptions: MaterialOptions(
actionBarColor: "#abcdef",
actionBarTitle: "Example App",
allViewTitle: "All Photos",
useDetailsView: false,
selectCircleStrokeColor: "#000000",
),
);
} on Exception catch (e) {
error = e.toString();
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
images = resultList;
_error = error;
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Center(child: Text('Error: $_error')),
RaisedButton(
child: Text("Pick images"),
onPressed: loadAssets,
),
Expanded(
child: buildGridView(),
)
],
),
),
);
}
}
Another way to fix using Stack
Stack(
children: <Widget>[
AssetThumb(
asset: asset,
width: 300,
height: 300,
),
Positioned(
right: -2,
top: -9,
child: IconButton(
icon: Icon(
Icons.cancel,
color: Colors.black.withOpacity(0.5),
size: 18,
),
onPressed: () => setState(() {
images.removeAt(index);
})))
],
);
You can try using Stack https://www.youtube.com/watch?v=liEGSeD3Zt8&vl=en
return Stack(
children: <Widget>[
AssetThumb(
asset: asset,
width: 300,
height: 300,
),
Positioned(
top: 0,
right: 0,
child: GestureDetector(
onTap: (){
print('delete image from List');
setState((){
print('set new state of images');
})
},
child: Icon(
Icons.delete,
),
),
),
],
);

Flutter - Relative Position Animations

Oops guys, how are you?
I am making an app using flutter and came across an issue related to animations.
Based on my study I wanted to make an animation where a center image on the screen after the animation is on top (topcenter).
But I didn't find a way to animate using relative values (for example the actual screen height value) only with values that I would describe (which causes problems on screens with different sizes).
Does anyone have any solutions?
AnimatedLogo({this.controller}) :
imagePosition = Tween(
begin: (Use screen size here without context),
end: (0 to topcenter)
).animate(
CurvedAnimation(
parent: controller,
curve: Interval(0.0, 0.150),
)
);
You have some options, you can use AnimatedContainer or AnimatedPositioned
All these options can use AlignmentDirectional.bottomCenter , topCenter
For other options, you can reference this https://medium.com/aubergine-solutions/options-to-animate-in-flutter-2cec6612c207
full code with AnimatedContainer
import 'package:flutter/material.dart';
import 'dart:ui';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: Option5()
);
}
}
class Option5 extends StatefulWidget {
#override
_Option5State createState() => _Option5State();
}
class _Option5State extends State<Option5> with TickerProviderStateMixin {
AlignmentDirectional _ironManAlignment = AlignmentDirectional.bottomCenter; //AlignmentDirectional(0.0, 0.7);
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/person-96.png'),
fit: BoxFit.cover)),
),
AnimatedContainer(
duration: Duration(seconds: 3),
alignment: _ironManAlignment,
child: Container(
height: 250,
width: 150,
child: Image.asset('assets/images/alarm-80.png'),
),
),
Align(
alignment: AlignmentDirectional.bottomCenter,
child: RaisedButton(
onPressed: () {
_flyIronMan();
},
child: Text('Go'),
color: Colors.red,
textColor: Colors.yellowAccent,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20))),
),
)
],
);
}
void _flyIronMan() {
setState(() {
_ironManAlignment = AlignmentDirectional.topCenter; //AlignmentDirectional(0.0,-0.7);
});
}
}

Resources