Reputation: 7092
I'm learning flutter and I want to build a simple app that updates a quote of the day when a button is pressed.
So I combined the default flutter app that is created automatically and a tutorial I found on the web.
The quote is displayed when the app loads, but I'm not quite sure how to update it when the button is pressed.
I tried putting this line in the _incrementCounter function, but it throws an error:
_saying = Quote();
A value of type 'Quote' can't be assigned to a variable of type 'String'.
Is there anyway to get the quote to update when I press the button?
Thanks!
--main
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
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'),
);
}
}
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;
String _saying = '';
String url = 'https://quotes.rest/qod.json';
void _incrementCounter() {
setState(() {
_counter++;
_saying = Quote();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("-- Quote of the Day --"),
Quote(),
Text(
'dYou have pushed the buttons this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class Quote extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _getQuote(),
builder: (context, snapshot) {
return snapshot.connectionState == ConnectionState.done
? Center(
child: Text(
snapshot.data,
textAlign: TextAlign.center,
))
: Center(child: CircularProgressIndicator());
});
}
}
Future<String> _getQuote() async {
final res = await http.get('http://quotes.rest/qod.json');
return json.decode(res.body)['contents']['quotes'][0]['quote'];
}
Upvotes: 0
Views: 271
Reputation: 599
You don't need _saying, change _incrementCounter like this
void _incrementCounter() {
setState(() {
_counter++;
});
}
Because you use setState, the build method will call again then it will recreate Quote thus it fetch data again. I suggest you read and try a better state management system like provider and bloc later. Hope this helps you.
Upvotes: 2