Suppose I have a SingleChildScrollView, its content is read from a file:
singleChildScrollView(
padding: EdgeInsets.all(8.0),
child: nw Text(
getTextFromFile(), //<---read from file
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
),
));
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
Future<String> getTextFromFile() async {
return getFileData("test.txt");
}
I got the following error:
The argument type 'Future<String>' can't be assigned to the parameter
type 'String'.
How to solve the issue?
Using a FutureBuilder should solve your problem. I modified you code so you can see how to use it. initialData is not required.
#override
Widget build(BuildContext context) {
return new FutureBuilder(
future: getTextFromFile(),
initialData: "Loading text..",
builder: (BuildContext context, AsyncSnapshot<String> text) {
return new SingleChildScrollView(
padding: new EdgeInsets.all(8.0),
child: new Text(
text.data,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
),
));
});
}
Future<String> getFileData(String path) async {
return await new Future(() => "test text");
}
Future<String> getTextFromFile() async {
return getFileData("test.txt");
}
}
StatefulWidget can be used for this purpose.
Declare a member variable String _textFromFile = ""; in your State class and update its value on future resolve by using setState() method.
I called your getTextFromFile() method from the constructor, but you may call it from anywhere.
Running code:
import 'package:flutter/material.dart';
import 'dart:async';
class StatefullWidgetDemo extends StatefulWidget {
#override
_StatefulWidgetDemoState createState() {
return new _StatefulWidgetDemoState();
}
}
class _StatefulWidgetDemoState extends State<StatefullWidgetDemo> {
String _textFromFile = "";
_StatefulWidgetDemoState() {
getTextFromFile().then((val) => setState(() {
_textFromFile = val;
}));
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Stateful Demo'),
),
body: new SingleChildScrollView(
padding: new EdgeInsets.all(8.0),
child: new Text(
_textFromFile,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
),
),
),
);
}
Future<String> getFileData(String path) async {
return "your data from file";
}
Future<String> getTextFromFile() async {
return await getFileData("test.txt");
}
}
Simple answer here=>
The class which calls the function:
#override
Widget build(BuildContext context) {
return new Scaffold(
child: FutureBuilder(
future: function(),
builder: (BuildContext context, AsyncSnapshot<String> text) {
return new Text(text.data);
});
)}
And the function:
Future<String> function() async {
return 'abc';
}
Here's a similar question:
flutter / dart error: The argument type 'Future<File>' can't be assigned to the parameter type 'File'
The solution proposed there is quite elegant and works properly. Where the IDE says it's expecting Type and not Future<Type>, put await in front of that argument
Another solution to get data on initialization would be to call getTextFromFile() in initState(), set state with new string and use that string in your widget:
String fileData = '';
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
void getTextFromFile() async {
try {
String data = await getFileData("test.txt");
setState(() {
fileData = data;
});
} catch (ex) {
print(ex);
}
}
#override
void initState() {
super.initState();
getTextFromFile();
}
new singleChildScrollView(
padding: new EdgeInsets.all(8.0),
child: new Text(
fileData,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
),
));
I would like to add one more answer, as I tested other answers I got an error.
Moving the async part (plus setState) from the constructor to initState() solved that for me.
Enjoy
class TestAsyncInStateful extends StatefulWidget {
const TestAsyncInStateful({super.key});
#override
State<TestAsyncInStateful> createState() => _TestAsyncInStatefulState();
}
class _TestAsyncInStatefulState extends State<TestAsyncInStateful> {
#override
void initState() {
super.initState();
getTextFromServer().then(
(value) => setState(() {
textFromServer = value;
}),
);
}
String? textFromServer;
#override
Widget build(BuildContext context) {
return textFromServer == null? const SizedBox() :Text(textFromServer!);
}
}
Related
I am trying to create a webview in Flutter that the user can as a web browser that injects some js code to the document before it is loads (atDocumentStart).
I have tries several ways but it always seems to inject the code too late (onload).
final String injectScript = ("some js code");
class WebPage extends StatefulWidget {
WebPage({Key key, this.title}) : super(key: key);
final String title;
#override
_WebPageState createState() => _WebPageState();
}
class _WebPageState extends State<WebPage> {
GlobalKey<ScaffoldState> scaffoldState;
bool isLoading = false;
final assetIdController = TextEditingController(text: "");
bool isValid = true;
static Completer<WebViewController> _webViewController =
Completer<WebViewController>();
#override
void initState() {
super.initState();
}
Widget favoriteButton() {
return FutureBuilder<WebViewController>(
future: _webViewController.future,
builder: (BuildContext context,
AsyncSnapshot<WebViewController> controller) {
if (controller.hasData) {
return FloatingActionButton(
onPressed: () async {
// TOO LATE HERE:
controller.data.evaluateJavascript(injectScript);
},
child: const Icon(Icons.refresh),
);
}
return Container();
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
key: scaffoldState,
appBar: AppBar(
centerTitle: true,
elevation: 0.0,
iconTheme: IconThemeData(color: Theme.of(context).primaryColor),
backgroundColor: Theme.of(context).canvasColor,
),
backgroundColor: const Color(0xFFF8F8F8),
body: WebView(
initialUrl: 'https://communities-qa.cln.network',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) async {
// NOT WORKING HERE:
// await webViewController.evaluateJavascript(injectScript);
_webViewController.complete(webViewController);
},
),
floatingActionButton: favoriteButton(),);
}
}
I expect it to load the code before the page (the page relies on the evaluated code to run). but it is either too late or not working.
I'm trying to change the state of isSyncing then rebuild the widget with set state once await api.fetchProducts() is completed. api.fetchProducts() is what i used to fetch from API then store local using sqflite.
I tried using cloudSyn.then() but it wont work.
class SyncProgress extends StatefulWidget {
#override
_SyncProgressState createState() => _SyncProgressState();
}
class _SyncProgressState extends State<SyncProgress> {
bool isSyncing = true;
String progressString = 'Syncing your data....';
final db = DatabaseHelper();
final bloc = ProductBloc();
#override
void initState() {
super.initState();
}
Future cloudSync() async{
await api.fetchProducts();
//Here is the challenge
setState(() {
isSyncing = false;
progressString = 'Syncing complete....';
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: isSyncing ? _indicateProgress() : _syncDone()
);
}
Widget _indicateProgress(){
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(height: 50.0,),
Text(progressString, style: TextStyle(
fontSize: 16.0,
),),
],
),
);
}
_syncDone(){
print('Syncing completed');
//return Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));
}
}
Use then to force setState function to execute only after fetchProducts() is finished:
Future cloudSync() async{
await api.fetchProducts().then(
setState(() {
isSyncing = false;
progressString = 'Syncing complete....';
});
);
}
I have this code that has the parent widget Homepage and the child widget CountryList. In CountryList, I have created a function that uses an API to get a list of countries. I felt like enabling a RefreshIndicator in the app, so I had to modify the Homepage widget and add GlobalKey to access getCountryData() function of CountryList widget. The RefreshIndicator has done its job well. But the problem now is that when I pull and use the RefreshIndicator in the app, the getCountryData() function is called, but even after showing all data in the list, the circular spinner doesn't go (shown in the screenshot).
So, could anyone please suggest me a way to make the spinner go?
The code of main.dart containing Homepage widget is given below:
import 'package:flutter/material.dart';
import 'country_list.dart';
GlobalKey<dynamic> globalKey = GlobalKey();
void main() => runApp(MaterialApp(home: Homepage()));
class Homepage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("List of countries"), actions: <Widget>[
IconButton(icon: Icon(Icons.favorite), onPressed: (){},)
],),
body: RefreshIndicator(child: CountryList(key:globalKey), onRefresh: (){globalKey.currentState.getCountryData();},),
);
}
}
And the code of country_list.dart containing CountryList widget is:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_svg/flutter_svg.dart';
class CountryList extends StatefulWidget {
CountryList({Key key}) : super(key: key);
#override
_CountryListState createState() => _CountryListState();
}
class _CountryListState extends State<CountryList> {
List<dynamic> _countryData;
bool _loading = false;
#override
void initState() {
// TODO: implement initState
super.initState();
this.getCountryData();
}
Future<String> getCountryData() async {
setState(() {
_loading = true;
});
var response =
await http.get(Uri.encodeFull("https://restcountries.eu/rest/v2/all"));
var decodedResponse = json.decode(response.body);
setState(() {
_countryData = decodedResponse;
_loading = false;
});
}
#override
Widget build(BuildContext context) {
return _loading?Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[CircularProgressIndicator(), Padding(padding: EdgeInsets.all(5.0),), Text("Loading data...", style: TextStyle(fontSize: 20.0),)],)):ListView.builder(
itemCount: _countryData.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: ListTile(
leading: SvgPicture.network(_countryData[index]['flag'], width: 60.0,),
title: Text(_countryData[index]['name']),
trailing: IconButton(
icon: Icon(Icons.favorite_border),
onPressed: () {},
),
),
);
},
);
}
}
You need to add return here:
Future<String> getCountryData() async {
setState(() {
_loading = true;
});
var response =
await http.get(Uri.encodeFull("https://restcountries.eu/rest/v2/all"));
var decodedResponse = json.decode(response.body);
setState(() {
_countryData = decodedResponse;
_loading = false;
});
return 'success';
}
and here:
body: RefreshIndicator(
child: CountryList(key: globalKey),
onRefresh: () {
return globalKey.currentState.getCountryData();
},
),
The onRefresh callback is called. The callback is expected to update the scrollable's contents and then complete the Future it returns. The refresh indicator disappears after the callback's Future has completed, I think you should return Future<String> from getCountryData.
i would love to call the Future fetchPost from a RaisedButton or in other words i don't wan't the FutureBuilder to do anything until i click the button, i tried calling fetchPost from the button but it won't work and I'm stuck.
PS: I used the example from this page https://flutter.io/cookbook/networking/fetch-data/
Your help is appreciated.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
class FirstFragment extends StatelessWidget {
FirstFragment(this.usertype,this.username);
final String usertype;
final String username;
#override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final Size screenSize = MediaQuery.of(context).size;
return new SingleChildScrollView(
padding: new EdgeInsets.all(5.0),
child: new Padding(
padding: new EdgeInsets.symmetric(vertical: 0.0, horizontal: 0.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Container(
child: new RaisedButton(
child: new Text('Call'),
onPressed: (){
fetchPost();
},
),
),
new Container(
child: FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
)
)
],
),
),
);
}
}
As Dhiraj explained above calling fetchPost alone won't change UI, so you need to reset UI by calling setState.
Below is how your code should look like
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
class FirstFragment extends StatefulWidget {
FirstFragment(this.usertype,this.username);
final String usertype;
final String username;
#override
_FirstFragmentState createState() => new _FirstFragmentState(usertype, username);
}
class _FirstFragmentState extends State<FirstFragment> {
_FirstFragmentState(this.usertype,this.username);
final String usertype;
final String username;
#override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final Size screenSize = MediaQuery.of(context).size;
return new SingleChildScrollView(
padding: new EdgeInsets.all(5.0),
child: new Padding(
padding: new EdgeInsets.symmetric(vertical: 0.0, horizontal: 0.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Container(
child: new RaisedButton(
child: new Text('Call'),
onPressed: (){
fetchPost();
setState(() {
});
},
),
),
new Container(
child: FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
)
)
],
),
),
);
}
}
Calling fetchPost alone wont do changes in UI.
At first inside build your futurebuilder is execcuted which gets data from fetchPost.
Further then to fetchPost agiain you need to rebuild.
To do so inside onPressed of raised button:
onPressed: (){
setState((){})
},
And to fetch post only on button click (not for first time) you should use then()
Details here : https://www.dartlang.org/tutorials/language/futures
I am trying to build a countdown widget. Currently, I got the structure to work. I only struggle with the countdown itself. I tried this approach using the countdown plugin:
class _Countdown extends State<Countdown> {
int val = 3;
void countdown(){
CountDown cd = new CountDown(new Duration(seconds: 4));
cd.stream.listen((Duration d) {
setState((){
val = d.inSeconds;
});
});
}
#override
build(BuildContext context){
countdown();
return new Scaffold(
body: new Container(
child: new Center(
child: new Text(val.toString(), style: new TextStyle(fontSize: 150.0)),
),
),
);
}
}
However, the value changes very weirdly and not smooth at all. It start twitching. Any other approach or fixes?
It sounds like you are trying to show an animated text widget that changes over time. I would use an AnimatedWidget with a StepTween to ensure that the countdown only shows integer values.
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class Countdown extends AnimatedWidget {
Countdown({ Key key, this.animation }) : super(key: key, listenable: animation);
Animation<int> animation;
#override
build(BuildContext context){
return new Text(
animation.value.toString(),
style: new TextStyle(fontSize: 150.0),
);
}
}
class MyApp extends StatefulWidget {
State createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
AnimationController _controller;
static const int kStartValue = 4;
#override
void initState() {
super.initState();
_controller = new AnimationController(
vsync: this,
duration: new Duration(seconds: kStartValue),
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.play_arrow),
onPressed: () => _controller.forward(from: 0.0),
),
body: new Container(
child: new Center(
child: new Countdown(
animation: new StepTween(
begin: kStartValue,
end: 0,
).animate(_controller),
),
),
),
);
}
}
The countdown() method should be called from the initState() method of the State object.
class _CountdownState extends State<CountdownWidget> {
int val = 3;
CountDown cd;
#override
void initState() {
super.initState();
countdown();
}
...
Description of initState() from the Flutter docs:
The framework calls initState. Subclasses of State should override
initState to perform one-time initialization that depends on the
BuildContext or the widget, which are available as the context and
widget properties, respectively, when the initState method is called.
Here is a full working example:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:countdown/countdown.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Countdown Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new CountdownWidget();
}
}
class _CountdownState extends State<CountdownWidget> {
int val = 3;
CountDown cd;
#override
void initState() {
super.initState();
countdown();
}
void countdown(){
print("countdown() called");
cd = new CountDown(new Duration(seconds: 4));
StreamSubscription sub = cd.stream.listen(null);
sub.onDone(() {
print("Done");
});
sub.onData((Duration d) {
if (val == d.inSeconds) return;
print("onData: d.inSeconds=${d.inSeconds}");
setState((){
val = d.inSeconds;
});
});
}
#override
build(BuildContext context){
return new Scaffold(
body: new Container(
child: new Center(
child: new Text(val.toString(), style: new TextStyle(fontSize: 150.0)),
),
),
);
}
}
class CountdownWidget extends StatefulWidget {
#override
_CountdownState createState() => new _CountdownState();
}
based on #raju-bitter answer, alternative to use async/await on countdown stream
void countdown() async {
cd = new CountDown(new Duration(seconds:4));
await for (var v in cd.stream) {
setState(() => val = v.inSeconds);
}
}
Why not use a simple TweenAnimationBuilder its easy to use and you don't need to manage any stream controllers or worry about using streams and disposing them off etc;
TweenAnimationBuilder<double>(
duration: Duration(seconds: 10),
tween: Tween(begin: 100.0, end: 0.0),
onEnd: () {
print('Countdown ended');
},
builder: (BuildContext context, double value, Widget child) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('${value.toInt()}',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 40)));
}),
here's the dartpad example to playaround
output:
originally answered here
Countdown example using stream, not using setState(...) therefore its all stateless.
this borrow idea from example flutter_stream_friends
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:countdown/countdown.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
static String appTitle = "Count down";
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: appTitle,
theme: new ThemeData(
primarySwatch: Colors.purple,
),
home: new StreamBuilder(
stream: new CounterScreenStream(5),
builder: (context, snapshot) => buildHome(
context,
snapshot.hasData
// If our stream has delivered data, build our Widget properly
? snapshot.data
// If not, we pass through a dummy model to kick things off
: new Duration(seconds: 5),
appTitle)),
);
}
// The latest value of the CounterScreenModel from the CounterScreenStream is
// passed into the this version of the build function!
Widget buildHome(BuildContext context, Duration duration, String title) {
return new Scaffold(
appBar: new AppBar(
title: new Text(title),
),
body: new Center(
child: new Text(
'Count down ${ duration.inSeconds }',
),
),
);
}
}
class CounterScreenStream extends Stream<Duration> {
final Stream<Duration> _stream;
CounterScreenStream(int initialValue)
: this._stream = createStream(initialValue);
#override
StreamSubscription<Duration> listen(
void onData(Duration event),
{Function onError,
void onDone(),
bool cancelOnError}) =>
_stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
// The method we use to create the stream that will continually deliver data
// to the `buildHome` method.
static Stream<Duration> createStream(int initialValue) {
var cd = new CountDown(new Duration(seconds: initialValue));
return cd.stream;
}
}
The difference from stateful is that reload the app will restart counting. When using stateful, in some cases, it may not restart when reload.