FutureBuilder return passed to var Flutter - flutter

I need to store some data inside a ".txt" file into a variable.
To do this I'm using a FutureBuilder.
The idea is to handle the reading action (async) with FutureBuilder and pass the FutureBuilder return to my global variable that will be updated when needed.
Future<String> _read() async {
try {
final file = await _localBio;
String body = await file.readAsString();
// Read the file.
return body;
} catch (e) {
// If encountering an error, return 0.
return "Can't read";
}
}
var bio ="";
String _ReadBio(){
FutureBuilder<String>(
future: _read(),
builder: (context, snapshot){
if (snapshot.hasData) {
bio=snapshot.data.toString(); //this isn't done
return Text("");
}
else {
return Text("Error occured");
}
}
);
return "";
}
Then in the TextField I want to show what is stored inside bio that should be the content of "bio.txt".
child: Text(
_ReadBio()== "" //always true if no error occured
? bio
: "Tell us something about you...",
),
But what is showed is the first bio value, I don't know why.

I strongly suggest you to read about FutureBuilder.
You are missing the point od FutureBuilder because its is a widget to place in a widget tree what you have done is placed on a function that returns a empty string.
Instead you can do it like this,
Future<Widget> _readAndBuildBioWidget(){
return FutureBuilder<String>(
future: _read(),
builder: (context, snapshot){
if (snapshot.hasData) {
bio=snapshot.data.toString(); //this isn't done
return Text(bio ?? "");
}
else {
return Text("Error occured");
}
}
);
return "";
}
#override
void build() {
return Scaffold(
child: _readAndBuildBioWidget(),
);
}
Or you can do as below,
class _HomeScreenState extends State<HomeScreen> {
var bio = "";
Future<String> _read() async {
try {
final file = await _localBio;
String body = await file.readAsString();
return body;
} catch (e) {
return "Can't read";
}
}
#override
void initState() {
_read().then((onValue) => bio = onValue);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text(bio ?? "")),
);
}
}
Note above code snippet I haven't tested. I just wanted to give a rough idea.

Related

Can I Use a Future<String> to 'Fill In' a Text() Widget Instead of Using FutureBuilder in Flutter?

I'm trying to better understand Futures in Flutter. In this example, my app makes an API call to get some information of type Future<String>. I'd like to display this information in a Text() widget. However, because my String is wrapped in a Future I'm unable to put this information in my Text() widget, and I'm not sure how to handle this without resorting to a FutureBuilder to create the small widget tree.
The following example uses a FutureBuilder and it works fine. Note that I've commented out the following line near the bottom:
Future<String> category = getData();
Is it possible to turn category into a String and simply drop this in my Text() widget?
import 'package:flutter/material.dart';
import 'cocktails.dart';
class CocktailScreen extends StatefulWidget {
const CocktailScreen({super.key});
#override
State<CocktailScreen> createState() => _CocktailScreenState();
}
class _CocktailScreenState extends State<CocktailScreen> {
#override
Widget build(BuildContext context) {
Cocktails cocktails = Cocktails();
Future<String> getData() async {
var data = await cocktails.getCocktailByName('margarita');
String category = data['drinks'][0]['strCategory'];
print('Category: ${data["drinks"][0]["strCategory"]}');
return category;
}
FutureBuilder categoryText = FutureBuilder(
initialData: '',
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
}
return const CircularProgressIndicator();
},
);
//Future<String> category = getData();
return Center(
child: categoryText,
);
}
}
Here's my Cocktails class:
import 'networking.dart';
const apiKey = '1';
const apiUrl = 'https://www.thecocktaildb.com/api/json/v1/1/search.php';
class Cocktails {
Future<dynamic> getCocktailByName(String cocktailName) async {
NetworkHelper networkHelper =
NetworkHelper('$apiUrl?s=$cocktailName&apikey=$apiKey');
dynamic cocktailData = await networkHelper.getData();
return cocktailData;
}
}
And here's my NetworkHelper class:
import 'package:http/http.dart' as http;
import 'dart:convert';
class NetworkHelper {
NetworkHelper(this.url);
final String url;
Future<dynamic> getData() async {
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
return decodedData;
} else {
//print('Error: ${response.statusCode}');
throw 'Sorry, there\'s a problem with the request';
}
}
}
Yes, you can achieve getting Future value and update the state based on in without using Using FutureBuilder, by calling the Future in the initState(), and using the then keyword, to update the state when the Future returns a snapshot.
class StatefuleWidget extends StatefulWidget {
const StatefuleWidget({super.key});
#override
State<StatefuleWidget> createState() => _StatefuleWidgetState();
}
class _StatefuleWidgetState extends State<StatefuleWidget> {
String? text;
Future<String> getData() async {
var data = await cocktails.getCocktailByName('margarita');
String category = data['drinks'][0]['strCategory'];
print('Category: ${data["drinks"][0]["strCategory"]}');
return category;
}
#override
void initState() {
super.initState();
getData().then((value) {
setState(() {
text = value;
});
});
}
#override
Widget build(BuildContext context) {
return Text(text ?? 'Loading');
}
}
here I made the text variable nullable, then in the implementation of the Text() widget I set to it a loading text as default value to be shown until it Future is done0
The best way is using FutureBuilder:
FutureBuilder categoryText = FutureBuilder<String>(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
var data = snapshot.data ?? '';
return Text(data);
}
}
},
),
but if you don't want to use FutureBuilder, first define a string variable like below and change your adasd to this :
String category = '';
Future<void> getData() async {
var data = await cocktails.getCocktailByName('margarita');
setState(() {
category = data['drinks'][0]['strCategory'];
});
}
then call it in initState :
#override
void initState() {
super.initState();
getData();
}
and use it like this:
#override
Widget build(BuildContext context) {
return Center(
child: Text(category),
);
}
remember define category and getData and cocktails out of build method not inside it.

call a build function in StatefullWidget after finish the Future function

i need to call and get the result from an async function before build the widget in statefulWidget in flutter, i tried to do like this, but it didn't work:
#override
void initState() {
super.initState();
loadDocument(details).whenComplete((){
setState(() {});
});
vid = YoutubePlayer.convertUrlToId(details);
}
#override
Widget build(BuildContext context) {
print("from details in build widget");
return Scaffold(
appBar: AppBar(
title: Text(name.toString()),
backgroundColor: Colors.redAccent,
),
body : Center(child: PDFViewer(document: controller.document)))
in this example, first thing call the function (loadDocument), after that call the (build) methode for widget, and then show the result after (whenComplete) has been finished, but what i need is to only call the build function after (whenComplete) finish....
this code for loadDocument
PDFDocument document = PDFDocument();
loadDocument(String url) async {
try {
return document = await PDFDocument.fromURL(
url);
} on Exception catch (e) {
print(e);
}
}
You can use FutureBuilder to build your ui based on the different Future states:
FutureBuilder<*Your future return type*>(
future: *Your future*,
builder: (BuildContext context, AsyncSnapshot<*Your future return type*> snapshot) {
if (snapshot.hasData) {
// Handle future resolved case
} else if (snapshot.hasError) {
// Handle future error case
} else {
// Handle future loading case
}
},
)
You can read more about FutureBuilder here: https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

Getx is not working properly with FutureBuilder for update list

I'm using the Getx controller in my project. I have create the controller for FutureBuilder for displaying list but .Obs is not set on Future Function. I'm sharing the code.
class PPHomeController extends GetxController {
Future<List<PPProductRenterModel>> listNearProduct;
// i want to set .Obs end of the "listNearProduct" but it's not working because of Future.
FetchNearProductList({#required int price}) async {
listNearProduct = CallGetNearProducts();// Http API Result
}
}
{
PPHomeController _homeController = Get.put(PPHomeController());
Widget mainProductListView() {
return FutureBuilder<List<PPProductRenterModel>>
(builder: (context, AsyncSnapshot<List<PPProductRenterModel>> projectSnap){
if(!projectSnap.hasData){
if(projectSnap.connectionState == ConnectionState.waiting){
return Container(
child: Loading(),
);
}
}
return ListView.builder(
itemCount: projectSnap.data.length,
itemBuilder: (context, index) {
PPProductRenterModel model = projectSnap.data[index];
PPPrint(tag: "CheckId",value: model.productId);
return ProductMainItemRow(model);
});
},
future: _homeController.listNearProduct,);
There is a cleaner way for implementing List in GetX without worrying about Type-Casting:
Instantiate it:
final myList = [].obs;
Assign it:
myList.assignAll( listOfAnyType );
(Reference) Flutter error when using List.value :
'value' is deprecated and shouldn't be used. List.value is deprecated.
use [yourList.assignAll(newList)]. Try replacing the use of the
deprecated member with the replacement.
Detailed code example
ProductController.dart
class ProductController extends GetxController {
final productList = [].obs;
#override
void onInit() {
fetchProducts();
super.onInit();
}
void fetchProducts() async {
var products = await HttpServices.fetchProducts();
if (products != null) {
productList.assignAll(products);
}
}
}
HttpServices.dart
class HttpServices {
static var client = http.Client();
static Future<List<Product>> fetchProducts() async {
var url = 'https://link_to_your_api';
var response = await client.get(url);
if (response.statusCode == 200) {
return productFromJson(response.body);
} else {
return null;
}
}
}
product.dart
class Product {
Product({
this.id,
this.brand,
this.title,
this.price,
....
});
....
}
Form the docs:
3 - The third, more practical, easier and preferred approach, just add
.obs as a property of your value:
final items = <String>[].obs;
Following that instruction, this should work:
final listNearProduct = Future.value(<PPProductRenterModel>[]).obs;
E.g.:
// controller
final list = Future.value(<String>[]).obs;
#override
void onInit() {
super.onInit();
fetchList();
}
Future<List<String>> callApi() async {
await Future.delayed(Duration(seconds: 2));
return ['test'];
}
void fetchList() async {
list.value = callApi();
}
// screen
#override
Widget build(BuildContext context) {
return GetX<Controller>(
init: Controller(),
builder: (controller) {
return FutureBuilder<List<String>>(
future: controller.list.value,
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data[0]); // Output: test
return Text(snapshot.data[0]);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
);
},
);
};
You never actually call FetchNearProductList.
You need to call it in some place, preferably before the FutureBuilder uses that Future.

Flutter nested provider not getting the latest values despite notifyListeners() being called

Say, I have 2 widgets, A and B, where B is nested inside A. Both widgets are wrapped using Consumer. However, only widget A is able to get latest values from the provider, whereas widget B remains as the initial state.
class WidgetA extends StatelessWidget {
Widget build(BuildContext context) {
final FooProvider fooProvider = Provider.of<FooProvider>(context, listen: false);
fooProvider.fetchData();
return Consumer<FooProvider>(
builder: (context, value, child) {
print(value.modelList[0].name); //able to get latest value whenever changes are made to FooProvider.
return GestureDetector(
onTap: () async {
foodProvider.fetchData();
return showDialog(
context: context,
builder: (BuildContext context) {
return WidgetB(); //NOTICE I'm calling WidgetB here
}
)
},
child: WidgetB(); //NOTICE I'm calling WidgetB here
);
}
)
}
}
class WidgetB extends StatelessWidget {
Widget build(BuildContext context) {
return Consumer<FooProvider>(
builder: (context, value, child) {
print(value.modelList[0].name); //unable to get latest in showDialog
return Container();
}
)
}
}
EDIT The code for ChangeNotifier:
It's just a regular Provider doing its work.
List<FooModel> modelList = [];
bool isWithinTimeFrame = false;
Future<void> fetchData(email, token, url) async {
await Service(
email,
token,
).fetchCutOff(url).then((response) {
if (response.statusCode == 200) {
var jsonResponse = json.decode(response.body.toString());
bool isSuccess = jsonResponse["success"];
if (isSuccess) {
dynamic formattedResponse = jsonResponse["data"];
List<FooModel> modelList = formattedResponse
.map<FooModel>((json) => FooModel.fromJson(json))
.toList();
setModelList(modelList);
setIsWithinTimeFrame(computeTime(modelList));
} else {}
} else {}
});
}
void setModelList(value) {
modelList = value;
notifyListeners();
}
void setIsWithinTimeFrame(value) {
isWithinTimeFrame = value;
notifyListeners();
}

Flutter: Future<String> returns null but if printing it has value

username is null but if I'm printing 'value' it contains some string, how can I get 'value'?
class HomeWrapper extends StatelessWidget {
final DataBaseServices _db = DataBaseServices();
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
String username;
_db.getUsername(user).then((value) => username = value);
print(username);
if(username != null){
return Home();
}else{
_db.createBlankUser(user);
return EditProfile();
}
}
.then() is called when the value of the Future is returned. So the value of value is always non null, whereas username is null when you print it.
Try the difference by replacing .then(...) with:
.then((value){
username = value;
print(username);
});
Additionally, you can have a look at how to handle Asynchronous data in Flutter
I'm guessing _db.getUsername is returning a Future?
In that case you should look into using FutureBuilder
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
return FutureBuilder(
builder: (context, snap) {
//snap.data will be the username
if(snap.hasData) {
return Home();
} else {
//you need to wait for another Future here I guess?
return FutureBuilder(
builder: (context, snap2){
if(snap2.connectionState == ConnectionState.done){
return EditProfile();
} else {
//return some sort of circular loader icon.
}
},
future: _db.createBlankUser(user)
);
}
},
future: _db.getUsername(user),
);