按下按钮时更新文本

时间:2019-12-09 20:09:39

标签: flutter

我正在学习抖动,我想构建一个简单的应用程序,该应用程序可以在按下按钮时更新当天的报价。

因此,我将自动创建的默认Flutter应用程序和我在网上找到的教程结合了起来。

在加载应用程序时会显示报价,但是我不确定在按下按钮时如何更新报价。

我尝试将这一行放在_incrementCounter函数中,但是会引发错误:

 _saying = Quote(); 
  

不能将类型为'Quote'的值赋给类型变量   “字符串”。

当我按下按钮时,是否还有报价更新?

谢谢!

-主要

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'];
}

1 个答案:

答案 0 :(得分:2)

您不需要_saying,像这样更改_incrementCounter

void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

由于使用setState,因此build方法将再次调用,然后将重新创建Quote,从而再次获取数据。我建议您稍后阅读并尝试使用更好的状态管理系统,例如provider和bloc。希望对您有帮助。