Why images didn't add to the imagescontainer in ListView - flutter

This is my code
If I push the button the image is showing after I press the "hot reload" button.
Question:
Why can't the images be added to the imagecontainer in ListView?
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Anime Randomizer'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var urlresult = "https://danbooru.donmai.us/data/original/13/c4/13c4ee9c0f8e305fbe6a4c4efb540ec7.jpg";
var filter = "";
var error = "";
var iterator = 0;
List<Widget> imagescontainer = [new Container(child: Image.network("https://danbooru.donmai.us/data/original/13/c4/13c4ee9c0f8e305fbe6a4c4efb540ec7.jpg", width: 400, height: 650)),];
void fetchAnimeUrl() async {
var url = Uri.parse('https://danbooru.donmai.us/posts/random?tags=rating%3Asafe${filter != null ? '+'+filter: ''}&format=json');
final response = await http.get(url);
if (response.statusCode == 200) {
var start = response.body.indexOf('file_url');
var end = response.body.indexOf(',"large_file_url"');
if(start != -1 || end != -1){
setState(() {
iterator++;
urlresult = response.body.substring(start + 11, end - 1);
error = imagescontainer.length.toString();
imagescontainer.add(new Container(child: Image.network(urlresult.toString(), width: 300, height: 620)));
});
}
else{
setState(() {
error = "Купить премиум - 25\$";
});
}
} else {
throw Exception('Failed to load anime');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Anime randomizer list"),
),
body: Container(
child: ListView(
scrollDirection: Axis.vertical,
children: imagescontainer //this variable contain all my images
),
),
floatingActionButton: FloatingActionButton(
onPressed: fetchAnimeUrl,
tooltip: 'MoreAnime',
child: Icon(Icons.arrow_circle_down),
),
);
}
}

I fix it!
body: Container(
child: ListView(
scrollDirection: Axis.vertical,
children: imagescontainer.toList() //i wrote a "toList()"
),
),

Related

Flutter: Error when displaying single list value

In Flutter I am reading a file from disk and displaying the list items as a list. Using ListView.builder works fine but with a text widget displaying a single value I get this error. Can someone help?
The error I get is The following RangeError was thrown building MyHomePage(dirty, state: _MyHomePageState#e9932):
RangeError (index): Invalid value: Valid value range is empty: 9
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'dart:async';
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(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
______________________________
WITH List.View.builder
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> _names = [];
Future<List<String>> loadNames() async {
List<String> names = [];
await rootBundle.loadString('assets/Stulkur_A.txt').then((q) => {
for (String i in LineSplitter().convert(q)) {names.add(i)}
});
return names;
}
_setup() async {
List<String> names = await loadNames();
setState(() {
_names = names;
});
}
#override
void initState() {
_setup();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Names'),
),
body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: ListView.builder(
itemCount: _names.length,
itemBuilder: (context, index) {
return Text(_names[index]);
})),
),
);
}
}
_____________________
WITH Text widget
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> _names = [];
Future<List<String>> loadNames() async {
List<String> names = [];
await rootBundle.loadString('assets/Stulkur_A.txt').then((q) => {
for (String i in LineSplitter().convert(q)) {names.add(i)}
});
return names;
}
_setup() async {
List<String> names = await loadNames();
setState(() {
_names = names;
});
}
#override
void initState() {
_setup();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Names'),
),
body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: Text(_names[9]),
),
),
);
}
}
Try
body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: _names.isEmpty
? CircularProgressIndicator()
: ListView.builder(
itemCount: _names.length,
itemBuilder: (context, index) {
return Text(_names[index]);
},
),
),
),
You should check if _names.length == 0 show a loader or everything you want otherwise show the ListView widget.

ImagePickerWeb Output is File$ instead of File

I am using ImagePickerWeb to allow users to upload photos from my app
Future<void> getPhotos() async {
var imageFile = await ImagePickerWeb.getImage(outputType: ImageType.file);
print(imageFile);
if (imageFile != null) {
setState(() {
currentSelfie = imageFile;
_accDetails['customer_selfie'] = currentSelfie;
});
}
When I try to display the image via Image.File
Image.file(
currentSelfie,
height: screenAwareSize(100, context),
width: screenAwareSize(100, context),
fit: BoxFit.fill,
),
I get this error
File$ ([object File]) :<getObject: NoSuchMethodError: The
getter 'uri' was called on null.>
I am using the file format for my because I am passing the image to my back end server and it receives the data as a file. Any help would be appreciated.
You can copy paste run full code below
According to owner's description https://github.com/Ahmadre/image_picker_web#how-do-i-get-all-informations-out-of-my-imagevideo-eg-image-and-file-in-one-run
You can use ImagePickerWeb.getImageInfo and show image with Image.memory
code snippet
Future<void> getPhotos() async {
var mediaData = await ImagePickerWeb.getImageInfo;
String mimeType = mime(Path.basename(mediaData.fileName));
html.File mediaFile =
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});
print("imageFile ${mediaData.toString()}");
if (mediaData != null) {
currentSelfie = mediaData.data;
setState(() {});
}
}
...
currentSelfie == null
? Container()
: Image.memory(
(currentSelfie),
fit: BoxFit.fill,
),
working demo
full code
import 'dart:async';
import 'dart:io';
import 'package:mime_type/mime_type.dart';
import 'package:path/path.dart' as Path;
import 'package:flutter/material.dart';
import 'package:image_picker_web/image_picker_web.dart';
import 'dart:html' as html;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var currentSelfie;
Future<void> getPhotos() async {
var mediaData = await ImagePickerWeb.getImageInfo;
String mimeType = mime(Path.basename(mediaData.fileName));
html.File mediaFile =
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});
print("imageFile ${mediaData.toString()}");
if (mediaData != null) {
currentSelfie = mediaData.data;
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
currentSelfie == null
? Container()
: Image.memory(
(currentSelfie),
fit: BoxFit.fill,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: getPhotos,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Flutter IgnorePointer for 2 fingers

I am trying to ignore multi-finger touches (2-finger specifically) on a Button by wrapping it with IgnorePointer() like so:
import 'package:flutter/material.dart';
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',
home: MyHomePage(title: '1 touch'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool isSingleTouch = true;
#override
Widget build(BuildContext context) {
return IgnorePointer(
ignoring: !isSingleTouch,
child: RaisedButton(
onPressed: () {
print("Button Tapped");
},
child: Text("Tap with max 1 finger."),
));
}
}
I want isSingleTouch to be true when the user uses one finger but false when he uses two fingers. Is there any way to get the number of fingers and if it is 2 then make the button fail the hit test?
Please check the below example to detect two figure touch. You can modify it as per your requirement.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Swipe Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Container(
margin: EdgeInsets.only(top: 100),
child: MultiTouchPage(
backgroundColor: Colors.white,
borderColor: Colors.amber,
minTouches: 2,
onTapCallback: (touchCount, correct) {
print("Touch" + touchCount.toString());
},
),
),
),
);
}
}
class MultiTouchGestureRecognizer extends MultiTapGestureRecognizer {
MultiTouchGestureRecognizerCallback onMultiTap;
var numberOfTouches = 0;
int minNumberOfTouches = 0;
MultiTouchGestureRecognizer() {
super.onTapDown = (pointer, details) => this.addTouch(pointer, details);
super.onTapUp = (pointer, details) => this.removeTouch(pointer, details);
super.onTapCancel = (pointer) => this.cancelTouch(pointer);
super.onTap = (pointer) => this.captureDefaultTap(pointer);
}
void addTouch(int pointer, TapDownDetails details) {
this.numberOfTouches++;
}
void removeTouch(int pointer, TapUpDetails details) {
if (this.numberOfTouches == this.minNumberOfTouches) {
this.onMultiTap(numberOfTouches, true);
} else if (this.numberOfTouches != 0) {
this.onMultiTap(numberOfTouches, false);
}
this.numberOfTouches = 0;
}
void cancelTouch(int pointer) {
this.numberOfTouches = 0;
}
void captureDefaultTap(int pointer) {}
#override
set onTapDown(_onTapDown) {}
#override
set onTapUp(_onTapUp) {}
#override
set onTapCancel(_onTapCancel) {}
#override
set onTap(_onTap) {}
}
typedef MultiTouchGestureRecognizerCallback = void Function(
int touchCount, bool correctNumberOfTouches);
class MultiTouchPage extends StatefulWidget {
final MultiTouchPageCallback onTapCallback;
final int minTouches;
final Color backgroundColor;
final Color borderColor;
MultiTouchPage(
{this.backgroundColor,
this.borderColor,
this.minTouches,
this.onTapCallback});
#override
_MultiTouchPageState createState() => _MultiTouchPageState();
}
class _MultiTouchPageState extends State<MultiTouchPage> {
bool correctNumberOfTouches;
int touchCount;
#override
Widget build(BuildContext context) {
return RawGestureDetector(
gestures: {
MultiTouchGestureRecognizer:
GestureRecognizerFactoryWithHandlers<MultiTouchGestureRecognizer>(
() => MultiTouchGestureRecognizer(),
(MultiTouchGestureRecognizer instance) {
instance.minNumberOfTouches = widget.minTouches;
instance.onMultiTap =
(touchCount, correctNumberOfTouches,) => this.onTap(touchCount, correctNumberOfTouches);
},
),
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(12.0),
decoration: BoxDecoration(
color: widget.backgroundColor,
border: Border(
top: BorderSide(width: 1.0, color: widget.borderColor),
left: BorderSide(width: 1.0, color: widget.borderColor),
right: BorderSide(width: 1.0, color: widget.borderColor),
bottom: BorderSide(width: 1.0, color: widget.borderColor),
),
),
child: Text(
"Tap with " +
this.touchCount.toString() +
" finger(s).",
textAlign: TextAlign.center),
),
),
]),
);
}
void onTap(int touchCount, bool correctNumberOfTouches) {
this.correctNumberOfTouches = correctNumberOfTouches;
setState(() {
this.touchCount = touchCount;
});
print("Tapped with " + touchCount.toString() + " finger(s)");
widget.onTapCallback(touchCount, correctNumberOfTouches);
}
}
typedef MultiTouchPageCallback = void Function(int touchCount, bool correctNumberOfTouches);

How to make pagination in case items as horizontal Scrolling not vertical listview builder in flutter?

I have horizontal listview builder so how to make pagination to load more data in case items for horizontal listview !
You can copy paste run full code below
You can use package https://pub.dev/packages/flutter_pagewise
code snippet
return PagewiseListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
pageSize: PAGE_SIZE,
itemBuilder: this._itemBuilder,
pageFuture: (pageIndex) =>
BackendService.getPosts(pageIndex * PAGE_SIZE, PAGE_SIZE));
working demo
full code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class PagewiseListViewExample extends StatelessWidget {
static const int PAGE_SIZE = 5;
#override
Widget build(BuildContext context) {
return PagewiseListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
pageSize: PAGE_SIZE,
itemBuilder: this._itemBuilder,
pageFuture: (pageIndex) =>
BackendService.getPosts(pageIndex * PAGE_SIZE, PAGE_SIZE));
}
Widget _itemBuilder(context, PostModel entry, _) {
return Container(
width: 200,
child: ListTile(
leading: Icon(
Icons.person,
color: Colors.brown[200],
),
title: Text(entry.title),
//subtitle: Text(entry.body),
),
);
}
}
class BackendService {
static Future<List<PostModel>> getPosts(offset, limit) async {
final responseBody = (await http.get(
'http://jsonplaceholder.typicode.com/posts?_start=$offset&_limit=$limit'))
.body;
// The response body is an array of items
return PostModel.fromJsonList(json.decode(responseBody));
}
static Future<List<ImageModel>> getImages(offset, limit) async {
final responseBody = (await http.get(
'http://jsonplaceholder.typicode.com/photos?_start=$offset&_limit=$limit'))
.body;
// The response body is an array of items.
return ImageModel.fromJsonList(json.decode(responseBody));
}
}
class PostModel {
String title;
String body;
PostModel.fromJson(obj) {
this.title = obj['title'];
this.body = obj['body'];
}
static List<PostModel> fromJsonList(jsonList) {
return jsonList.map<PostModel>((obj) => PostModel.fromJson(obj)).toList();
}
}
class ImageModel {
String title;
String id;
String thumbnailUrl;
ImageModel.fromJson(obj) {
this.title = obj['title'];
this.id = obj['id'].toString();
this.thumbnailUrl = obj['thumbnailUrl'];
}
static List<ImageModel> fromJsonList(jsonList) {
return jsonList.map<ImageModel>((obj) => ImageModel.fromJson(obj)).toList();
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(height: 200, child: PagewiseListViewExample()),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Child widget send dynamic data

I have a two-page app. On-Page One I am showing an UUID which changes every 1 second. It is shown using listview. Once the user clicks on the list view it goes to the second page and shows the data on that card.
It should have been the changing UUID. but the data shown is static UUID. How I can pass the data changed on page 1 to page 2?
import 'dart:async';
import 'package:uuid/uuid.dart';
import 'package:uuid/uuid_util.dart';
import 'package:flutter/material.dart';
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(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
List<EuropeanCountries> europeanCountries = [];
class EuropeanCountries {
String myText;
String myUuid;
EuropeanCountries({
this.myText,
this.myUuid,
});
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
int _perPage = 50;
ScrollController _myScrollController = ScrollController();
void _incrementCounter() async {
const ThreeSec = const Duration(seconds: 1);
this._counter++;
europeanCountries.insert(
0,
EuropeanCountries(
myText: this._counter.toString(),
));
print(europeanCountries[0].myText);
setState(() {});
}
void getMoreData() {
print('adding More Product ');
europeanCountries.add(EuropeanCountries(
myText: this._counter.toString(),
));
//europeanCountries.insert(0, EuropeanCountries(myText:this._counter.toString(), myButtonText: "", myColor: Colors.blue));
setState(() {});
}
void generateUUID() async {
var uuid = Uuid();
for (int i = 0; i < 6000; i++) {
await new Future.delayed(new Duration(milliseconds: 1000));
for (EuropeanCountries currCountry in europeanCountries) {
currCountry.myUuid = uuid.v1();
}
setState(() {});
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
generateUUID();
_myScrollController.addListener(() {
double maxscroll = _myScrollController.position.maxScrollExtent;
double currentScroll = _myScrollController.position.pixels;
double delta = MediaQuery.of(context).size.height * 0.25;
print("mac Scroll Controller - " + maxscroll.toString());
print("Current Scroll Controller - " + currentScroll.toString());
print("delta Scroll Controller - " + delta.toString());
if ((maxscroll - currentScroll) < delta) {
getMoreData();
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _myListView(context),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget _myListView(BuildContext context) {
// backing data
return Container(
child: europeanCountries.length == 0
? Center(
child: Text('No Product to Display'),
)
: ListView.builder(
controller: _myScrollController,
itemCount: europeanCountries.length,
reverse: false,
itemBuilder: (context, index) {
return myContainer(index: index);
},
),
);
}
}
class myContainer extends StatefulWidget {
final int index;
const myContainer({Key key, this.index}) : super(key: key);
#override
_myContainerState createState() => _myContainerState();
}
class _myContainerState extends State<myContainer> {
#override
Widget build(BuildContext context) {
return Container(
height: 120,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue[700]),
shape: BoxShape.rectangle,
borderRadius: BorderRadius.all(Radius.circular(8)),
),
margin: EdgeInsets.all(20),
child: Column(
children: <Widget>[
Text(europeanCountries[widget.index].myText),
SizedBox(
height: 15,
),
RaisedButton(
child: Text('Detail'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondRoute(
myCountry: europeanCountries[widget.index],
)),
);
},
color: Colors.blue[700],
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
splashColor: Colors.black,
),
Text(europeanCountries[widget.index].myUuid != null
? europeanCountries[widget.index].myUuid
: 'Default')
],
),
);
}
}
class SecondRoute extends StatefulWidget {
final EuropeanCountries myCountry;
const SecondRoute({Key key, this.myCountry}) : super(key: key);
#override
_SecondRouteState createState() => _SecondRouteState();
}
class _SecondRouteState extends State<SecondRoute> {
#override
void didUpdateWidget(SecondRoute oldWidget) {
// TODO: implement didUpdateWidget
super.didUpdateWidget(oldWidget);
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Text(widget.myCountry.myUuid != null
? widget.myCountry.myText
: 'default'),
),
SizedBox(height: 15),
Center(
child: Text(widget.myCountry.myUuid != null
? widget.myCountry.myUuid
: 'default'),
),
],
),
),
),
);
}
}
https://imgur.com/VqRfcZY
<blockquote class="imgur-embed-pub" lang="en" data-id="VqRfcZY"></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>