How hold the splash screen till data are ready - android

Is it possible that the spash screen (launch screen)
is shown till the data needed for the app is ready?
Are there other options in manifest.xml as below?
"io.flutter.app.android.SplashScreenUntilFirstFrame"

After many retries I found a solution which could be optimized.
Please tell me your opinion
Normally flutter starts with
void main() => runApp(new MyApp());
I inserted the data acquisition on the begin by modifying the code
void main() async {
final OrderedAppList aList = new OrderedAppList(); //class to get all data
var funx = (int) async => aList.getit(); //to get all of the data
var value;
value = await funx(1); //should wait for the return value
runApp(new MyApp(
qallUserApps: aList.allUserApps,
qlistLen: value, // means aList.listLen,
qplatformVersion: aList.platformVersion,
qmodel: aList.model
));
}
And in MyApp:
class MyApp extends StatelessWidget {
final List qallUserApps;
final int qlistLen;
final String qplatformVersion;
final String qmodel;
// Constructor:
const MyApp({Key key, this.qallUserApps,
this.qlistLen,
this.qplatformVersion,
this.qmodel})
: super(key: key);
#override
Widget build(BuildContext context) {
// ...
}
Code part of the class OrderedAppList:
class OrderedAppList {
int listLen= -1;
String platformVersion = "Unknown Platform";
String model = "Unknown Platform";
List allUserApps = null;
Future<int> getit() async {
try {
allUserApps = await AppsAsStateless.allApps;
listLen = allUserApps.length;
} on Exception {
allUserApps = null;
listLen = 0;
}
// ...
return listLen ;
}
Thanks for reading this!

it works fine and
the code in main can be optimized:
void main() async { // async that data acquisition done before any widgets shown
final OrderedAppList aList = new OrderedAppList();
int value;
value = await aList.getit();
runApp(new MyApp(
qallUserApps: aList.allUserApps,
qlistLen: value, // = aList.listLen,
qplatformVersion: aList.platformVersion,
qmodel: aList.model
));
}

Related

2 Problems from Flutter Beginner Course from Angela, Clima project after refactoring code

1) From loading_screen.dart :
Error : Instance member 'getData' can't be accessed using static access.
Locator( ) is my location handling class.
import 'package:flutter/material.dart';
import 'package:clima/services/location_handler.dart';
import 'package:clima/services/networking.dart';
const myAPI = 'cant post api online but its just alphabets and numbers passed as a string';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
late double latitood;
late double longitood;
void initState() {
//this method is called the moment we run our app.
super.initState();
getLocationData();
}
void getLocationData() async {
Locator loca = Locator();
await loca.getCurrentLocation();
latitood = loca.latitude;
longitood = loca.longitude;
NetworkHelper NetHelp = NetworkHelper(
//pasing url info into Network Helper class.
'https://api.openweathermap.org/data/2.5.weather?lat=$latitood&lon=$longitood&appid=$myAPI');
var weatherDataFinal = await NetworkHelper.getData();
}
#override
Widget build(BuildContext context) {
return Scaffold();
}
}
2) From networking.dart :
Error : The argument type 'String' can't be assigned to the parameter type 'Uri'.
import 'dart:convert'; /
import 'package:http/http.dart' as http;
class NetworkHelper {
NetworkHelper(this.url);
final String url;
Future getData() async {
http.Response response = await http.get(url);
//passing url as a single string to get method to get Response.
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
//decoding and putting data into decodedData variable of dynamic type.
return decodedData;
} else {
print(response.statusCode);
}
}
}
Did someone encounter these problems ? If you did and found a Solution then please help me !!!!
This await NetworkHelper.getData(); should be await NetHelp.getData(); because that is how you named your variable.
await http.get(url); should be await http.get(Uri.parse(url));

I'm creating an app using dart for a list view of images

Basically, I'm learning Dart for the first time. I'm still learning the syntax and everything.
I have created four files
1.main dart
2.app dart
3.image_list dart
4.image_model dart
enter image description here
I am pasting the code here please can anyone help me.
Thank you in advance.
Image_model
class ImageModel {
int id;
String url;
String title;
ImageModel(this.id, this.url, this.title);
ImageModel.fromJson(Map<String, dynamic> parsedJson)
:id = parsedJson['id'],
url = parsedJson['url'],
title = parsedJson['title'];
}
Image_list
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 Text(images[index].url);
},
);
}
}
some part of app dart
class AppState extends State<App> {
int counter = 0;
List<ImageModel> images = [];
void fetchImage() async {
counter++;
String url = "https://jsonplaceholder.typicode.com/photos/$counter";
var response = await http.post(Uri.parse(url));
var image_model = ImageModel.fromJson(json.decode(response.body));
setState(() {
images.add(image_model);
});
}
The data coming in parsedJson variable might have Id null or not an int. can you check.

How do I make setState run from Class ? flutter

I need to use a command in class other
Example
I need to use a command in class other
Example
import 'package:flutter/material.dart';
class SelectionUser {
BuildContext _context;
var _pagy;
int n = 0;
open(int x) {
n = x * 10;
setState(() {}); //////////////////////////////
}
SelectionUser(this._context, this._pagy);
}
You can pass a VoidCallback parameter to your class like this:
import 'package:flutter/material.dart';
class Example extends State<...>{
#override
void initState(){
super.initState();
final user = SelectionUser(() => setState((){}), null)
}
...
}
class SelectionUser {
SelectionUser(this._setState, this._pagy);
var _pagy;
VoidCallback _setState;
int n = 0;
open(int x) {
n = x * 10;
_setState(); //////////////////////////////
}
}
Then your user.open() will call the _setState callback that triggers the setState as required
The fact that you need a BuildContext in your class and you want to call setState makes it obvious that you should not have a simple class, but instead inherit from StatefulWidget and State<>.
More information on how to do so can be found in the documentation.

GetStorage always returns null in flutter

Code
print("Before : ${GetStorage().read("XXX")}");
GetStorage().write("XXX", 1);
print("After : ${GetStorage().read("XXX")}");
This is my Code. Every time I run the App, the Output is
Before : null
After : 1
Why is the storage data getting cleared everytime I restart the App? I thought this was an alternative to SharedPreference which works just fine. Have I missed something?
Before anything, initialize the package, normally I do this on main.dart
main() async {
await GetStorage.init();
}
Create an instance from GetStorage, I always put a name on the box, if not it will put "GetStorage" by default. It needs to have a name so it can retrieve your data.
GetStorage getStorage = GetStorage('myData');
After that you can write and retrieve data from it, I recommend you to "await" all reads and writes.
await getStorage.write('XXX', 1);
var a = await getStorage.read('XXX');
print(a); /// 1
I recommend you to put a name on the box according to what you are storing.
You should await for GetStorage.init().
void main() async {
await GetStorage.init();
print("Before : ${GetStorage().read("XXX")}");
GetStorage().write("XXX", 1);
print("After : ${GetStorage().read("XXX")}");
}
final _userBox = () => GetStorage('User');
class UserPref {
void call(){
_userBox.call()..initStorage;
}
dynamic setValueInt(String key, int value) {
return 0.val(key, getBox: _userBox).val = value;
}
String setValue(String key, String value) {
return ''.val(key, getBox: _userBox).val = value;
}
dynamic getValueInt(String key) {
return (-1).val(key,getBox: _userBox).val;
}
dynamic getValue(String key) {
return ''.val(key,getBox: _userBox).val;
}
void setUser(User user) {
''.val('uname', getBox: _userBox).val = user.uname ?? '';
(-1).val('gender', getBox: _userBox).val = user.gender ?? -1;
''.val('born', getBox: _userBox).val = user.born.toString();
true.val('enabled', getBox: _userBox).val = user.enabled ?? true;
}
User getUser() {
final String? uname = ''.val('uname',getBox: _userBox).val;
final int? gender = (-1).val('gender',getBox: _userBox).val;
final DateTime? born = ''.val('born',getBox: _userBox).val == '' ? null : DateTime.parse(''.val('born',getBox: _userBox).val);
final bool? enabled = true.val('enabled',getBox: _userBox).val;
return User(
uname: uname,
gender: gender,
born: born,
enabled: enabled,
);
}
}
///INIT:
#override
void initState() {
//The init function must be written separately from the read/write function due to being asynchronous.
UserPref().call();
}
//OR
Future<void> main() async {
//await GetStorage.init();
UserPref().call();
}
///USAGE:
class MyStatefulWidget extends StatefulWidget {
final Users prefUser = UserPref().getUser();
...
}
//OR
#override
Widget build(BuildContext context) {
final Users prefUser = UserPref().getUser();
return ...;
}

How to return Future<object> and assign it to just object , flutter

I have a custom class that fetches data from the database, that returns Future<List<Line>>, which lies in line_list.dart files :
Future<List<Line>> fetchingLinesData() async {
List<Line> lineList = [];
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'main.db');
Database database = await openDatabase(path, version: 1);
database.transaction((tnx) async {
dbRef.child('line').once().then((DataSnapshot dataSnapshot) async {
dataSnapshot.value.forEach((key, value) async {
List<Station> inLineStations = [];
for (var i = 0; i < 100; i++) {
if (value["station_$i"] != null) {
List<Map> stations = await tnx.rawQuery("SELECT * FROM Station");
stations.forEach((s) {
if (s['stationName'] == value["station_$i"]) {
Station stationInstance = Station(
key: s['key'],
cityName: s['cityName'],
stationName: s['stationName'],
stationLongitude: s['stationLongitude'],
stationLatitude: s['stationLatitude']);
inLineStations.add(stationInstance);
}
});
}
}
Line lineInstance = Line(
startStation: value['start_station'],
endStation: value['end_station'],
inLineStations: inLineStations,
notes: value['notes'],
price: value['price'],
transportationType: value['transportation_type']);
lineList.add(lineInstance);
});
});
});
return lineList;
}
}
and then in my main.dart widget, I have this :
List<Line> allLines = [];
I want to do something like this :
allLines = LinesList().fetchingLinesData();
But of course, it gives me an error as am trying to assign Future<List<Line>> to List<Line>
how to do it?
You have to await for future to complete.
allLines = await LinesList().fetchingLinesData();
You would just put the code below in a async function make main async and make your code
allLines = await LinesList().fetchingLinesData();

Categories

Resources