dart - 从 RaisedButton 调用 FutureBuilder

标签 dart flutter

我很乐意从 RaisedButton 调用 Future fetchPost 或者换句话说,我不希望 FutureBuilder 在我点击按钮之前做任何事情,我尝试从按钮调用 fetchPost 但它不起作用,我被卡住了。

PS:我使用了此页面中的示例 https://flutter.io/cookbook/networking/fetch-data/

感谢您的帮助。

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();
                },
              )
            )
          ],
        ),
      ),
    );

  }
}

最佳答案

正如 Dhiraj 上面解释的那样,单独调用 fetchPost 不会更改 UI,因此您需要通过调用 setState 来重置 UI。

下面是你的代码应该是什么样子

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();
                },
              )
            )
          ],
        ),
      ),
    );

  }
}

关于dart - 从 RaisedButton 调用 FutureBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100204/

相关文章:

ios - 在 [appName] : Flutter Firebase Plugin 中打开

flutter - 我如何在我的 API 请求类(无小部件类)中访问 bloc

flutter - Flutter:WAITINGHTTP请求进入循环

object - 创建一个对象并编码数据 Flutter

flutter - 如何修复导致: pub get failed(69)的错误

performance - 文本域 Controller 方法使性能下降

regex - Dart 从 URL 字符串中提取主机

android-studio - On Formatting Android Studio 在 Flutter 项目中展开 Dart 代码

flutter - 如何将 Flutter 桌面应用程序发布到 Windows 应用商店

json - 解析 JSON API 响应