I want to load a layout (mostly images) in the background with cached_network_image in flutter.
I used Splashscreen and this code, but it's not working. Do you have any ideas or maybe a better solution?
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:login/packages/intro_slider.dart';
import 'package:login/packages/splashscreen.dart';
class TestPage extends StatefulWidget{
#override
State<StatefulWidget> createState() => _TestPage();
}
class _TestPage extends State<TestPage>{
List<Slide> slides = new List();
String pageOne = "";
String pageTwo = "";
getData() async{
var userName = "";
final response =
await http.post('http://test.com/api',body: {"something":userName});
if (response.statusCode == 200) {
// If server returns an OK response, Return pinCode
var js = jsonDecode(response.body);
pageOne = js[0]['pic1'].toString();
pageTwo = js[0]['pic2'].toString();
slides.add(
new Slide(
backgroundImage: "https://test.com/pic/" + pageOne,
backgroundOpacity: 0,
),
);
slides.add(
new Slide(
backgroundImage: "https://test.com/pic/" + pageTwo,
backgroundOpacity: 0,
),
);
return await new Future<Widget>.delayed(
new Duration(
seconds: 1
), () => slider()
);
}
}
#override
void initState() {
super.initState();
}
Widget slider(){
return Scaffold(
body: new IntroSlider(
slides: this.slides,
),
);
}
#override
Widget build(BuildContext context) {
return new SplashScreen(
loadingData: getData,
image: new Image.asset("assets/images/logo.png"),
);
}
}
And, I try to cached image in intro_slider:
PinchZoomImage(
image: CachedNetworkImage(
imageUrl: backgroundImage,
),
hideStatusBarWhileZooming: true,
),
Related
Im triying to load a pdf file and render it in screen with the following code:
import 'package:flutter/material.dart';
import 'package:pdf_viewer_plugin/pdf_viewer_plugin.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import 'dart:developer';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
FileLoad createState() => FileLoad();
}
class FileLoad extends State<MyApp> {
String _filePath = "";
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test PDF',
theme: ThemeData(primarySwatch: Colors.blue,),
home:
Scaffold(
backgroundColor: Colors.grey,
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"),
BottomNavigationBarItem(icon: Icon(Icons.folder), label: "Load File")
],
onTap: (int index) async {
var go = 1;
if (index == 1) {
var status = await Permission.storage.status;
if (status != PermissionStatus.granted) {
var result = await Permission.storage.request();
if (result != PermissionStatus.granted) {
go = 0;
}
}
if (go == 1) {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path!);
setState(() {
_filePath = file.path;
log('_filePath: $_filePath');
});
}
}
}
},
),
body:
PdfView(path: _filePath, gestureNavigationEnabled: true,)
)
);
}
I can see the log with the correct filepath selected in the explorer, but nothing is rendered in the screen. What is wrong with the code?
Any error is triggered in the console.
For me it looks like that the PdfView itself doesn't load the newest path even with a setState(). I had this problem with other PDF-Viewer plugins.
I solved it by wrapping the PDFView into a if statement and while there is no path loaded some sort of loading Widget is displayed.
Like so:
String? _filePath;
body:
_filePath != null ? PdfView(path: _filePath, gestureNavigationEnabled: true,): Text("loading")
I wrote this code recently but it doesn't get me the result!
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'package:pics/src/widgets/image_list.dart';
import 'models/image_model.dart';
import 'dart:convert';
class App extends StatefulWidget {
createState() {
return AppState();
}
}
class AppState extends State<App> {
int counter = 0;
List<ImageModel> images = [];
void fetchImage() async {
counter++;
final Uri rep =
Uri.parse('https://jsonplaceholder.typicode.com/photos/$counter');
var response = await get(rep);
var imageModel = ImageModel.fromJson(json.decode(response.body));
setState(() {
images.add(imageModel);
});
}
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: ImageList(images),
appBar: AppBar(
title: const Text('Lets see some images'),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: fetchImage,
),
),
);
}
}
The terminal say this:
The following NetworkImageLoadException was thrown resolving an image
codec: HTTP request failed, statusCode: 403,
https://via.placeholder.com/600/92c952
When the exception was thrown, this was the stack:
#0 NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:117:9)
Image provider: NetworkImage("https://via.placeholder.com/600/92c952",
scale: 1.0) Image key:
NetworkImage("https://via.placeholder.com/600/92c952", scale: 1.0)
and this is image list class if you need to read it:
import 'package:flutter/material.dart';
import '../models/image_model.dart';
class ImageList extends StatelessWidget {
final List<ImageModel> images;
ImageList(this.images);
Widget build(context) {
return ListView.builder(
itemCount: images.length,
itemBuilder: (context, int index) {
return Image.network(images[index].url);
},
);
}
}
and this is Image Model:
class ImageModel {
late int id;
late String title;
late String url;
ImageModel(this.id, this.title, this.url);
ImageModel.fromJson(Map<String, dynamic> parsedJson) {
id = parsedJson['id'];
title = parsedJson['title'];
url = parsedJson['url'];
}
}
You can use web render, run with --web-renderer html
flutter run -d c --web-renderer html
-d to select device, where c is chrome
I get the error below after modifying my home page on my app to the code as shown below, I get the error in my object_patch.dart file. I don't know how that can be resolved. what could I have done wrong?
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: ) (see image)
import 'package:awsome_app/drawer.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
#override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
//Functions here now
// var myText = "This is a function";
// TextEditingController _nameController = TextEditingController();
var url = "https://jsonplaceholder.typicode.com/photos";
var data;
#override
void initState() {
// TODO: implement initState
super.initState();
fetchData();
}
fetchData() async {
var res = await http.post(Uri.parse(url));
data = jsonDecode(res.body);
setState(() {});
;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(204, 255, 249, 249),
appBar: AppBar(title: const Text("Welcome to Flutter App")),
body: data != null
? ListView.builder(
itemBuilder: (context, index) {
return ListTile(
title: Text(data[index]["title"]),
);
},
itemCount: data.length,
)
: Center(
child: CircularProgressIndicator(),
)
);
}
}```
GET https://jsonplaceholder.typicode.com/photos will return a list of photos.
Replace
var res = await http.post(Uri.parse(url));
with
var res = await http.get(Uri.parse(url));
I have written the following code below in Flutter
import 'dart:ui';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(Myapp());
class Myapp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Hello World'),
centerTitle: true,
backgroundColor: Colors.blueAccent,
),
body: Center(child: MyStatefulWidget(),
),
)
);
}
}
class Weather extends StatefulWidget {
UpdateTextState createState() => UpdateTextState();
}
class UpdateTextState extends State {
// var textHolder = 'Getting';
weath() async {
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.latitude);
print(position.longitude);
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=${position.latitude}&lon=${position.longitude}&appid=myapiid';
print(url);
var response = await http.get(url);
var dart = json.decode(response.body);
var dartt = dart['main'];
var climate = dartt['temp'];
var weather = climate - 32 * 5/9;
// print('Response status: ${response.statusCode}');
// print('Response body: ${json.decode(response.body)}');
// print(dart['main']);
// print(dartt['temp']);
var textHolder = '${weather.toString()}C';
return textHolder;
}
#override
Widget build(BuildContext context) {
var c = weath();
//print(textHolder);
//changeText();
return Scaffold(
body: Center(child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
child: Text(c),
),
]))
);
}
}
if I run this program this is the output I am getting Please refer to This image actually I want the weather that I get from the API which is text holder variable please Help me guys I have even tried without return statement too also I have tried adding the function directly which also didn't work out well basically is there any alternate way or did I make any mistake in the code
It's a Future so you can call it in your initState and use setState to update the c variable. or you can use FutureBuilder.
class Weather extends StatefulWidget {
UpdateTextState createState() => UpdateTextState();
}
class UpdateTextState extends State {
var c = 'Getting';
weath() async {
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.latitude);
print(position.longitude);
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=${position.latitude}&lon=${position.longitude}&appid=myapiid';
print(url);
var response = await http.get(url);
var dart = json.decode(response.body);
var dartt = dart['main'];
var climate = dartt['temp'];
var weather = climate - 32 * 5/9;
// print('Response status: ${response.statusCode}');
// print('Response body: ${json.decode(response.body)}');
// print(dart['main']);
// print(dartt['temp']);
var textHolder = '${weather.toString()}C';
setState(() {
c = textHolder;
});
}
#override
void initState() {
super.initState();
weath();
}
#override
Widget build(BuildContext context) {
var c = weath();
//print(textHolder);
//changeText();
return Scaffold(
body: Center(child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
child: Text(c),
),
]))
);
}
}
Just use setState((){}). Don't use return weath(), because async is a background thread and textView need UI.
var c = "";
#override
void initState() {
super.initState();
weath()
}
weath() async {
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=${position.latitude}&lon=${position.longitude}&appid=myapiid';
print(url);
var response = await http.get(url);
var dart = json.decode(response.body);
var dartt = dart['main'];
var climate = dartt['temp'];
var weather = climate - 32 * 5/9;
setState(() {
c = '${weather}C'; } );
}
Add Future as return type, as you are returning the value inside async function
Future<String> weath() async {
Modify the Build method like
Widget build(BuildContext context) {
return FutureBuilder(
future: weath(),
builder: (ctx, snapshot) {
return Scaffold(
body: Center(
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
child: Text(snapshot.data.toString()),
),
])));
});
}
I would like to make an endlessFeed in Fluter but the app terminates without giving me any information why. Basically it happens after I scrolled down about 60 images then it starts to lag a bit and it crashes.
I tested another API but the same there. It uses images with lower resolution so it takes longer to scroll down until it stops working.
So I don't know what happens here. My guess is that there are to many images in the ListView so that the phone can't handle it and crashes.
I've put the whole code below because I don't even know wehere the problem could be. Is there maybe another way to achieve an endlessImageFeed?
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:cached_network_image/cached_network_image.dart';
// my base url
String imageUrl = "http://192.168.2.107:8000";
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'EndlessFeed',
theme: ThemeData(
primaryColor: Colors.white,
),
home: PhotoList(),
);
}
}
class PhotoList extends StatefulWidget {
#override
PhotoListState createState() => PhotoListState();
}
class PhotoListState extends State<PhotoList> {
StreamController<Photo> streamController;
List<Photo> list = [];
#override
void initState() {
super.initState();
streamController = StreamController.broadcast();
streamController.stream.listen((p) => setState(() => list.add(p)));
load(streamController);
}
load(StreamController<Photo> sc) async {
// URL for API
String url = "http://192.168.2.107:8000/api/";
/* ______________________________________________
I also tried another API but it chrashes also (but it takes longer until crash):
String url = "https://jsonplaceholder.typicode.com/photos/";
______________________________________________ */
var client = new http.Client();
var req = new http.Request('get', Uri.parse(url));
var streamedRes = await client.send(req);
streamedRes.stream
.transform(UTF8.decoder)
.transform(json.decoder)
.expand((e) => e)
.map((map) => Photo.fromJsonMap(map))
.pipe(sc);
}
#override
void dispose() {
super.dispose();
streamController?.close();
streamController = null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("EndlessFeed"),
),
body: Center(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) => _makeElement(index),
),
),
);
}
Widget _makeElement(int index) {
if (index >= list.length) {
return null;
}
return Container(
child: Padding(
padding: EdgeInsets.only(top: 20.0),
child: Column(
children: <Widget>[
child: new Container(
// my base URL + one image
child: new Image(image: new CachedNetworkImageProvider(imageUrl + list[index].mImage))
),
),
],
),
));
}
}
class Photo {
final String mImage;
Photo.fromJsonMap(Map map)
: mImage= map['mImage'];
}